Javascript saves the page as a picture with the help of the html2canvas library

  • 2020-03-30 03:54:37
  • OfStack

The first step, the web page is saved as a Canvas, Canvas by html2canvas library, http://html2canvas.hertzen.com/


html2canvas(document.getElementById("id1"), { 
onrendered: function(canvas) { 
document.getElementById("id2").appendChild(canvas);//What to do after the canvas is generated, of course, you can open it in a new TAB, show it in a floating layer, etc.
}, 
canvas_id: 'canvas'//Add the canvas id by modifying the html2canvas source code
});

Note: the first parameter of html2canvas() is the area to generate canvas. If the entire web page generates canvas, it is document.body. The second parameter is detailed in the official website to set various canvas properties. Of course, you can modify the source code to add properties you want, such as adding id to the canvas.

Second, save the canvas generated in the first step as a picture


var canvas = document.getElementById("<span style="font-family: Arial, Helvetica, sans-serif;">canvas"</span><span style="font-family: Arial, Helvetica, sans-serif;">),</span> 
url = canvas.toDataURL();// 
//The following code is to download this picture function
var triggerDownload = $("<a>").attr("href", url).attr("download", "img.png").appendTo("body"); 
triggerDownload[0].click(); 
triggerDownload.remove();

Here you can focus on the toDataURL() method. You can convert the canvas into the image url in the form of data and assign this url to < Img / > The TAB displays the image, and the rest of the code is the download you need.


Related articles: