assets.forEach(function(v) {
var canvas = document.createElement('canvas');
canvas.id = "canvas" + v.name;
canvas.width = 200;
canvas.height = 150;
var ctx = canvas.getContext("2d");
var img = new Image();
img.src = 'file:///path/to/file/' + v.name;
img.onload = function () {
ctx.drawImage(img, 0, 0, img.width, img.height-256, 0, 0, 200, 150);
};
// This is working. Renders correctly and visible.
$('#test2').append(canvas);
chrome.downloads.download({
url: canvas.toDataURL(),
filename: 'file:///path/to/file/test-' + canvas.id + '.png'
});
});
大家好,这是我上面的代码。我想要的是下载一个较小版本img
的图像。一切正常,画布已创建,我可以在附加到元素$('#test2').append(canvas);
时看到它。但是当我想下载它时,它会下载空白。
我该如何解决这个问题?
答案 0 :(得分:2)
在download
处理程序中调用Image.onload
方法,因为调用download
方法时,Image
尚未绘制
assets.forEach(function(v) {
var canvas = document.createElement('canvas');
canvas.id = "canvas" + v.name;
canvas.width = 200;
canvas.height = 150;
var ctx = canvas.getContext("2d");
var img = new Image();
img.src = 'file:///path/to/file/' + v.name;
img.onload = function() {
ctx.drawImage(img, 0, 0, img.width, img.height - 256, 0, 0, 200, 150);
$('#test2').append(canvas);
chrome.downloads.download({
url: canvas.toDataURL(),
filename: 'file:///path/to/file/test-' + canvas.id + '.png'
});
};
});