Search code examples
javascriptjqueryhtml2canvas

Converting a table to canvas and then downloading the canvas as image using jQuery


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.


Solution

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