0

I'm using HTML2Canvas to convert a table to canvas and then I try to download the image using a download button. My code is as below:

$("input[alt='save-image']").click(function() {
  html2canvas($("table"), {
      onrendered: function(canvas) {
          this.href = canvas.toDataURL();
          this.download = "mypainting.png";
      }
  });
});

The table converts to image; however, the image never downloads. Please let me know if I'm doing anything wrong or if you would like to know more information.

Andrew Fakhry
  • 70
  • 1
  • 1
  • 11

2 Answers2

2

You can download image like this -

                html2canvas($('table').get(0)).then( function (canvas) {
                    // document.body.appendChild(canvas);//                        
                    var a = document.createElement('a');
                    // toDataURL defaults to png, so we need to request a jpeg, then convert for file download.
                    //a.href = canvas.toDataURL("image/jpeg").replace("image/jpeg", "image/octet-stream");
                    a.href = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
                    a.download = 'mypainting.png';
                    a.click();  
                });
T.Shah
  • 2,768
  • 1
  • 14
  • 13
1

I made it to work, thanks to T.Shah, and here is my final code:

$("input[alt='save-image']").click(function() {
  html2canvas($("table").get(0), {
    onrendered: function (canvas) {
      var a = document.createElement('a');
      a.href = canvas.toDataURL("image/png");
      a.download = 'Pixel-Drawing.png';
      a.click();
    }
  });
});
Andrew Fakhry
  • 70
  • 1
  • 1
  • 11