Sometimes, we want to take a screenshot of a div with JavaScript.
In this article, we’ll look at how to take a screenshot of a div with JavaScript.
How to take a screenshot of a div with JavaScript?
To take a screenshot of a div with JavaScript, we use the html2canvas library.
For instance, we write
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
Then we write
const canvas = await html2canvas(document.querySelector("#capture"));
const base64Data = canvas.toDataURL().replace("data:image/png;base64,", "");
const contentType = "image/png";
const linkSource = `data:${contentType};base64,${base64Data}`;
const downloadLink = document.createElement("a");
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();
to select the div with querySelector
.
Then we call html2canvas
to return a promise with the linkSource
URL.
We then create a link with createElement
.
We set its href
to the linkSource
base64 URL with the div’s image.
And then we set download
to the fileName
of the downloaded file.
Finally, we call click
to download the file.
Conclusion
To take a screenshot of a div with JavaScript, we use the html2canvas library.