html2canvas is a very famous open source library for taking screenshots from browser web pages. It is easy to use and has powerful functions.
Using html2canvasThe use of html2canvas is very simple. It is as simple as passing in a DOM element and then getting the canvas through callback:
In actual use, there are two points to note:1.html2canvas generates canvas image content by parsing the actual style of the element, so it has requirements for the actual layout and visual display of the element. If you want to take a complete screenshot, it is best to separate the element from the document flow (such as position:absolute)
2. The canvas image generated by default is very blurry on retina devices. Processing it into a 2x image can solve this problem:
var w = $(#code).width(); var h = $(#code).height();//Set the width and height of the canvas to 2 times the width and height of the container var canvas = document.createElement(canvas ); canvas.width = w * 2; canvas.height = h * 2; canvas.style.width = w + px; canvas.style.height = h + px; var context = canvas.getContext(2d);//Then scale the canvas and double the image to draw on the canvas context.scale(2,2); html2canvas(document.querySelector(#code), { canvas: canvas, onrendered: function (canvas) { ... } }); Practical examples of using html2canvas1.html code structure
<section class=share_popup id=html2canvas> <p>The use of html2canvas is very simple, as simple as passing in a DOM element and then getting the canvas through a callback</p> <p><img src=1.jpg>< /p> <p>The use of html2canvas is very simple, as simple as passing in a DOM element and then getting the canvas through a callback</p> </section>
2.js code structure
var str = $('#html2canvas'); //console.log(str); html2canvas([str.get(0)], { onrendered: function (canvas) { var image = canvas.toDataURL(image/png) ; var pHtml = <img src=+image+ />; $('#html2canvas').html(pHtml); } }); SummarizeThe above is the editor's introduction to how to use html2canvas to convert html code into images. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. I would also like to thank everyone for your support of the VeVb martial arts website!