首页 > 解决方案 > 使用 html2Canvas 创建下载 png 时出现以下错误

问题描述

在创建一个网站时,我正在使用html2canvas它将文本转换为图像。转换已成功完成,但在尝试单击按钮下载时,出现以下错误: 错误屏幕截图

任何人都可以帮我解决这个问题吗?

PS:我是网页设计的新手

html2canvas(document.getElementById("myname"), {
  onrendered: function (canvas) {
    var screenshot = canvas.toDataURL("image/png");
    document.getElementById("textScreenshot").setAttribute("src", screenshot);
  },
});

btnDownload.addEventListener("click", function () {
  if (window.navigator.msSaveBlob) {
    window.navigator.msSaveBlob(textScreenshot.msToBlob(), "sg.png");
  } else {
    const a = document.createElement("a");
    document.body.appendChild(a);
    a.href = screenshot.toDataURL();
    a.download = "sg.png";
    a.click();
    document.body.removeChild(a);
  }
});

错误:texttoimg.html:99 未捕获的 ReferenceError:屏幕截图未在 HTMLButtonElement 中定义。

标签: javascripthtmlcsshtml2canvas

解决方案


发生这种情况是因为您的screenshot变量在本地范围内适用于您的onrendered函数。您需要将其取出并存储在全局变量中,以便能够在其他函数中访问它。

let screenshot; // making it global 
window.onload = function(){
    html2canvas(document.getElementById("myname"), {
      onrendered: function (canvas) {
        screenshot = canvas.toDataURL("image/png");
        document.getElementById("textScreenshot").setAttribute("src", screenshot);
      },
    });
 }

btnDownload.addEventListener("click", function () {
  if (window.navigator.msSaveBlob) {
    window.navigator.msSaveBlob(textScreenshot.msToBlob(), "sg.png");
  } else {
    const a = document.createElement("a");
    document.body.appendChild(a);
    a.href = screenshot; // remote toDataURL from here
    a.download = "sg.png";
    a.click();
    document.body.removeChild(a);
  }
});

推荐阅读