Create a div image and save as

I would like to create a save image input button that:

  • Take a screenshot of the div
  • ask "Save As" on the user computer.

I found how to create a dive screen using html2canvas and open it in a new tab, it works fine:

function printDiv2(div) { html2canvas((div), { onrendered: function(canvas) { var img = canvas.toDataURL(); window.open(img); } }); } 

But for you, Save as part, it's kind of the hard part ... I found interesting topics, since I'm new to JS (and object) coding, I'm a little confused ... I think I will have to use FileSaver.js and create new blob http://eligrey.com/blog/post/saving-generated-files-on-the-client-side/

But I don’t understand how to implement saveAs in my html2canvas, how to draw a new blob correctly ...

 function printDiv2(div) { html2canvas((div), { onrendered: function(canvas) { var img = canvas.toDataURL(); window.open(img); var blob = new Blob(img, {type: "image/jpeg"}); var filesaver = saveAs(blob, "my image.png"); } }); } 

I also tried to do something with this by extracting the base64 source URL, but for me it is too hard to understand: http://bl.ocks.org/nolanlawson/0eac306e4dac2114c752

But will someone give me some advice and help me?

+8
javascript base64 blob html2canvas
source share
3 answers

Here is the final code if it can help you:

 function PrintDiv(div) { html2canvas((div), { onrendered: function(canvas) { var myImage = canvas.toDataURL(); downloadURI(myImage, "MaSimulation.png"); } }); } function downloadURI(uri, name) { var link = document.createElement("a"); link.download = name; link.href = uri; document.body.appendChild(link); link.click(); //after creating link you should delete dynamic link //clearDynamicLink(link); } 
+3
source share

You can do this approach:

  //Creating dynamic link that automatically click function downloadURI(uri, name) { var link = document.createElement("a"); link.download = name; link.href = uri; link.click(); //after creating link you should delete dynamic link //clearDynamicLink(link); } //Your modified code. function printToFile(div) { html2canvas(div, { onrendered: function (canvas) { var myImage = canvas.toDataURL("image/png"); //create your own dialog with warning before saving file //beforeDownloadReadMessage(); //Then download file downloadURI("data:" + myImage, "yourImage.png"); } }); } 
+3
source share

You looked

http://eligrey.com/demos/FileSaver.js/

Looks like he does what you need.

+1
source share

All Articles