How to save img to user's local computer using HTML2canvas

TheGrayVacuum picture TheGrayVacuum · Jul 27, 2015 · Viewed 63.2k times · Source

I'm rendering a screenshot onclick with HTML2canvas .4.1 and want to save the image to user's local computer. How can this be accomplished? Please note that I'm a beginner, so actual code will be most helpful to me.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="html2canvas.js"></script>

<button id="save_image_locally">download img</button>

   <div id="imagesave">
      <img id='local_image' src='img1.jpg'>
   </div>

<script>

    $('#save_image_locally').click(function(){

            html2canvas($('#imagesave'), 
             {
                onrendered: function (canvas) {
                    var img = canvas.toDataURL("image/png");
                    alert('This will currently open image in a new window called "data:". Instead I want to save to users local computer. Ideally as a jpg instead of png.');
                    window.open(img);
                }
             });
            });

</script>

Answer

2pha picture 2pha · Jul 27, 2015

NOTE: this answer is from 2015 and the library has been updated.
Check the answers below for alternate implementations.

Try this (Note that it makes use of the download attribute. See the caniuse support table for browsers that support the download attribute)

<script>

  $('#save_image_locally').click(function(){
    html2canvas($('#imagesave'), 
    {
      onrendered: function (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.download = 'somefilename.jpg';
        a.click();
      }
    });
  });

</script>