JS method to convert html into image format: first use html2canvas to convert html into canvas; then use the canvas object method [toDataURL()] to convert canvas into image.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, DELL G3 computer. This method is suitable for all brands of computers.
JS method of converting html into image format:
1. First, use html2canvas to convert html into canvas
html2canvas($('#content'),{ onrendered: function(canvas) { document.body.appendChild(canvas); } })
2. Use canvas object Method: toDataURL() converts canvas into image
function convertCanvasToImage(canvas) { var image = new Image(); image.src = canvas.toDataURL("image/png"); return image; }
The obtained data format is: data:image/png;base64...
The complete code is as follows:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Document</title> <script src="jquery.min.js"></script> <script src="html2canvas.js"></script> </head> <body> <div id="content" style="width:150px;height:150px;border:1px solid blue;"> <span>Hello World!</span> <br> <span><h2>Are you hear me?</h2></span> </div> <button id="btnSave">save</button> <script> $(function(){ $('#btnSave').click(function(event) { html2canvas($('#content'),{ onrendered: function(canvas) { document.body.appendChild(canvas); convertCanvasToImage(canvas); } }) }); function convertCanvasToImage(canvas) { var image = new Image(); image.src = canvas.toDataURL("image/png"); document.body.appendChild(image); return image; } }) </script> </body> </html>
Related free learning recommendations: javascript video tutorial
The above is the detailed content of How to convert html into image format using js. For more information, please follow other related articles on the PHP Chinese website!