下载空白页面(toDataURL())

时间:2016-07-19 19:49:41

标签: javascript google-chrome-extension

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);时看到它。但是当我想下载它时,它会下载空白。

我该如何解决这个问题?

1 个答案:

答案 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'
    });
  };
});