Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html2canvas

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> 
like image 937
TheGrayVacuum Avatar asked Jul 27 '15 15:07

TheGrayVacuum


People also ask

How to download div content as image using JavaScript?

DIV content can be saved as an image with the help of html2canvas() function in JavaScript. DIV tag defines a section in HTML document.

How do I use html2canvas in react?

How is it used? To render an element with html2canvas, use the following syntax: html2canvas(element[options]); The html2canvas function accepts the DOM element and returns a P``romise containing the <canvas> element.

How do I use canvas2image?

Use html2canvas. js to take a screenshot of a specific div and then use canvas2image. js to download the screenshot as an image locally to your filesystem.


1 Answers

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> 
like image 196
2pha Avatar answered Sep 27 '22 23:09

2pha