Welcome folks today in this blog post we will be using the html2canvas
library to take the screenshot of the website and exports it as png image in browser using javascript. All the full source code of the example as shown below
Full Example
Here we will be the full example to take the full screenshot of the html
body using the html2canvas.js
library. For this you need to make an index.html
file and copy paste the below code
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>Html2Canvas.js Example in Browser</title> </head> <style> * { background: rgb(32, 32, 32); color: whitesmoke; font-family: avenir, arial; padding: 10px; border-radius: 10px; } #content{ margin:50px; padding:50px; } </style> <body> <div id="content"> <p>Content here</p> </div> <button id="download-page-as-image">Download Page as Image</button> </body> <script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script> <script src="script.js"></script> </html> |
Now inside this html
document we have the div
tag inside that we have the paragraph. And then we have the button to export to image.
And also we are including the html2canvas cdn.
And now we will write the javascript code to export the website html to image.
script.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
// html2canvas <- https://html2canvas.hertzen.com/dist/html2canvas.min.js // code reference: https://stackoverflow.com/questions/31656689/how-to-save-img-to-users-local-computer-using-html2canvas setUpDownloadPageAsImage(); function setUpDownloadPageAsImage() { document.getElementById("download-page-as-image").addEventListener("click", function() { html2canvas(document.body).then(function(canvas) { console.log(canvas); simulateDownloadImageClick(canvas.toDataURL(), 'file-name.png'); }); }); } function simulateDownloadImageClick(uri, filename) { var link = document.createElement('a'); if (typeof link.download !== 'string') { window.open(uri); } else { link.href = uri; link.download = filename; accountForFirefox(clickLink, link); } } function clickLink(link) { link.click(); } function accountForFirefox(click) { // wrapper function let link = arguments[1]; document.body.appendChild(link); click(link); document.body.removeChild(link); } |
Here in the above section of javascript code we have provided the reference to the actual body of the html. And after that we have the callback function inside that we have the canvas. After that we are exporting the canvas to image using the toDataURL()
method. And also we are downloading the image using the anchor
element