简体   繁体   中英

I am getting following error while creating download png using html2Canvas

While creating a website I was using html2canvas which is going to convert text to an image. Conversion is done successfully but while trying to download on button click, I got the following error: Error Screenshot

Can anyone help me out with this please?

PS: I am completely new in web designing

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

Error:texttoimg.html:99 Uncaught ReferenceError: screenshot is not defined at HTMLButtonElement.

This is happening because your screenshot variable is locally scoped to your onrendered function. You need to take it out and store in a global variable to be able to access it in the other function.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM