I. Reference Library
Download address of html2canvas.js and canvas2image.js:
html2canvas.js: http://html2canvas.hertzen.com/dist/html2canvas.min.js
canvas2image.js: https://github.com/SuperAL/canvas2image/blob/master/canvas2image.js
Two, use
The jQ library needs to be introduced. If the browser is not introduced, you can import it yourself
http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js
Synchronous writing
function save_html_as_png(filename = 'image') { var opts = { //scale: scale, / / scale parameter added //canvas: canvas, / / custom canvas //logging: false, / / the log switch is used to view the internal execution process of html2canvas //width: width, //dom original width //height: height, useCORS: true // [important] enable cross domain configuration }; html2canvas($('body')[0], opts).then(canvas => { //document.body.appendChild(canvas); // canvas width var canvasWidth = canvas.width; // canvas height var canvasHeight = canvas.height; console.log(canvasHeight, canvasWidth); //sleep(2); // Call the Canvas2Image plug-in var img = Canvas2Image.convertToImage(canvas, canvasWidth, canvasHeight); // Call the Canvas2Image plug-in Canvas2Image.saveAsImage(canvas, canvasWidth, canvasHeight, 'png', filename); console.log('ok'); }); }
Asynchronous writing
async function async_save_html_as_png(filename="image") { var opts = { //scale: scale, / / scale parameter added //canvas: canvas, / / custom canvas //logging: false, / / the log switch is used to view the internal execution process of html2canvas //width: width, //dom original width //height: height, useCORS: true // [important] enable cross domain configuration }; var canvas = await html2canvas($('body')[0], opts); // canvas width var canvasWidth = canvas.width; // canvas height var canvasHeight = canvas.height; console.log(canvasHeight, canvasWidth); //sleep(2); // Call the Canvas2Image plug-in var img = Canvas2Image.convertToImage(canvas, canvasWidth, canvasHeight); // Call the Canvas2Image plug-in Canvas2Image.saveAsImage(canvas, canvasWidth, canvasHeight, 'png', filename); console.log('ok'); }
Just call the program I packed.
Key points:
1. html2canvas passed in the dom object. This is an asynchronous function. You can take a screenshot to specify the element area.
2. The default useCORS of html2canvas is False (cross domain). If not, cross domain pictures cannot be loaded in the screenshot.
3. Canvas2Image.convertToImage is a synchronization function. You can specify a picture area size. The type can be jpeg/png/bmp, etc. (case insensitive). The filename does not need a suffix. Canvas2Image.convertToImage only downloads picture files. Unable to store to the specified path.