Search code examples
javascripthtmlcsshtml2canvas

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.


Solution

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