Javascript 使用toBlob下载画布图像

Javascript 使用toBlob下载画布图像,javascript,html,canvas,Javascript,Html,Canvas,我试图在以下代码中使用toBlob点击按钮下载一个大画布图像(数千像素的高度和宽度),这似乎不起作用: document.getElementById("download_button").onclick = function() { var link = document.createElement("a"); link.download = "image.png"; canvas.toBlob(function(blob){ link.href = URL.creat

我试图在以下代码中使用
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,键入:“image/png”}

但是
console.log(link.href)
不返回任何内容

我是否未正确使用
.createObjectURL


我以前使用的是
toDataURL
,但它在超过某个画布大小时停止工作。这篇文章建议你试试toBlob,你的代码很好。。在合适的时间使用它:)


我的解决方案是:

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 });

好的,谢谢!它可以与
console.log(link.href)正常工作
链接。单击()
在回调函数中。@ymz为什么会这样?我认为只有当.href是添加到link元素的自定义属性时才会出现这种情况,但事实并非如此,然而,link元素也是在事件函数作用域中定义的,因此也应该可以访问,还是因为它嵌套在另一个函数中?@ymz我刚刚尝试了一些东西来测试它,我得到的结果是:
var link=document.createElement(“a”);link.download=“image.png”;函数test(){link.href=“#test”;console.log(link.href)}
result:“image.png”此外,我的第一个想法是link.href不应该在该函数之外访问,或者至少基于上述行为返回“image.png”,这很奇怪,但是函数范围之外的link.href给出了一个空字符串。
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 });