使用toBlob下载画布图像

时间:2017-06-15 12:26:47

标签: javascript html5 canvas

我试图在下面的代码中使用toBlob点击一个按钮下载一个大的画布图像(几千像素的高度和宽度),这似乎不起作用:

document.getElementById("download_button").onclick = function() {

  var link = document.createElement("a");
  link.download = "image.png";

  canvas.toBlob(function(blob){
    link.href = URL.createObjectURL(blob);
    console.log(blob);
  },'image/png');

  console.log(link.href);
  link.click();

}
回调函数中的

console.log(blob)返回:Blob {size: 64452, type: "image/png"}

console.log(link.href)没有任何回报。

我没有正确使用.createObjectURL吗?

我曾经使用过toDataURL,但它在某个画布大小之上停止了工作。此帖canvas.toDataURL() download size limit建议您尝试toBlob

2 个答案:

答案 0 :(得分:8)

您的代码很好..只需在合适的时间使用它:)

 canvas.toBlob(function(blob){
    link.href = URL.createObjectURL(blob);
    console.log(blob);
    console.log(link.href); // this line should be here
  },'image/png');

答案 1 :(得分:1)

我对问题的解决方案:

async function getImage({
  canvas,
  width,
  height,
  mime = 'image/jpeg',
  quality = 0.8,
}) {
  return new Promise(resolve => {
    const tmpCanvas = document.createElement('canvas');
    tmpCanvas.width = width;
    tmpCanvas.height = height;

    const ctx = tmpCanvas.getContext('2d');
    ctx.drawImage(
      canvas,
      0,
      0,
      canvas.width,
      canvas.height,
      0,
      0,
      width,
      height,
    );

    tmpCanvas.toBlob(resolve, mime, quality);
  });
}

const photo = await getImage({ canvas, width: 500, height: 500 });