Home > Article > Web Front-end > Javascript saves web pages as images with the help of html2canvas library_javascript skills
The first step is to save the web page as a Canvas canvas, using the html2canvas library, http://html2canvas.hertzen.com/
html2canvas(document.getElementById("id1"), { onrendered: function(canvas) { document.getElementById("id2").appendChild(canvas);//生成画布后如何处理,当然可以在新标签打开,在浮层展示等等 }, canvas_id: 'canvas'//通过修改html2canvas源码添加canvas的id });
Note: The first parameter of html2canvas() is the area where canvas is to be generated. If the canvas is generated for the entire web page, it is document.body. For the second parameter, please refer to the official website to set the various attributes of the canvas. Of course, you can modify the source code to add the attributes you want, such as adding an id to the canvas.
The second step is to 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();// //以下代码为下载此图片功能 var triggerDownload = $("<a>").attr("href", url).attr("download", "img.png").appendTo("body"); triggerDownload[0].click(); triggerDownload.remove();
Just focus on the toDataURL() method here. You can convert the canvas into an image URL in the form of data. Assign this URL to the 79d7c95122630a3791db16c5259dc98d tag to display the image. The other parts of the code are the download functions you need. .