Explain Codes LogoExplain Codes Logo

How to take a screenshot of a div with JavaScript?

javascript
html2canvas
promises
cross-browser
Nikita BarsukovbyNikita Barsukov·Aug 6, 2024
TLDR

To capture a screenshot of a div in a jiffy, use the html2canvas library:

html2canvas(document.getElementById('targetDiv')).then(canvas => { // In-page preview, like a movie trailer, // But for screenshots! document.body.appendChild(canvas); // Auto-download the PNG, like a ninja! const link = document.createElement('a'); link.download = 'div-screenshot.png'; link.href = canvas.toDataURL(); link.click(); });

Don't forget to make sure targetDiv matches the ID of the div you wish to capture. This code changes that div into a canvas and starts an image download, all without any server-side action involved.

Detailed drill-down

Let's dig more into the various aspects of taking a screenshot and how we can increase its functionality and smoothness.

Fancy-schmancy download

If you want to download the screenshot with a specific filename (because, why not?), use FileSaver.js:

html2canvas(document.querySelector("#targetDiv")).then(canvas => { canvas.toBlob(blob => { // Save the div, but with STYLE! saveAs(blob, "custom-filename.png"); }); });

Share the joy

If not saving and bucket-loading isn't enough, and you want to share your screenshots (because sharing is caring!), consider integrating your application with social media APIs or using a custom PHP script to handle the image data.

And because you'd rather meet a UFO than a securit breach, always validate the image data for security and reliability.

See before you leap

What's this? An opportunity to make the UX more interactive by offering a preview? Sure, why not!

html2canvas(document.getElementById('targetDiv')).then(canvas => { // It's like window shopping, but for screenshots! const imgPreview = document.createElement('img'); imgPreview.src = canvas.toDataURL(); document.body.appendChild(imgPreview); // Adjust it so it fits with your UI });

Dynamic content

If you're trying to conquer the ever-dynamic content like Google Maps, then use html2canvas with specific options to cater to the complexities (no, it won't give you directions to the nearest Starbucks!)

html2canvas(document.getElementById('map'), { useCORS: true, taintTest: false, allowTaint: true }).then(canvas => { // The world is now your playground! });

Cross-origin content

What do you do when your div content comes from different origins? You handle it like a pro, manage the security concerns, and enable CORS (because dealing with cross-origin issues should be as easy as crossing the road!)

Browser compatibility

Let's make sure that all users, irrespective of browser choice, can use your nifty screenshot feature. Always check the cross-browser compatibility for the libraries and methods you're using. Better safe than sorry!

Asynchronous handling with promises

If you want to tackle html2canvas like a true warrior, familiarize yourself with JavaScript Promises because it works like the distant cousin of synchro diving, only asynchronously:

html2canvas(document.getElementById('asyncDiv')).then(canvas => { // A-sync, B-sync, we all sync for JS Promises! });

Customization at its finest

Feeling artsy? Add watermarks, text, or art to your screenshots by leveraging canvas 2D drawing functions:

html2canvas(document.getElementById('customDiv')).then(canvas => { const ctx = canvas.getContext('2d'); // Let's make it prettier with some text! ctx.font = '20px Arial'; ctx.fillStyle = 'red'; ctx.fillText('Watermark', canvas.width - 100, canvas.height - 20); // And, action! });