Categories
JavaScript Answers

How to generate an image of a div and save the image to disk with JavaScript?

Spread the love

Sometimes, we want to generate an image of a div and save the image to disk with JavaScript.

In this article, we’ll look at how to generate an image of a div and save the image to disk with JavaScript.

How to generate an image of a div and save the image to disk with JavaScript?

To generate an image of a div and save the image to disk with JavaScript, we can use the html2canvas library.

For instance, we write:

<script src='https://html2canvas.hertzen.com/dist/html2canvas.min.js'></script>

<div id="capture" style="padding: 10px; background: #f5da55">
  <h4 style="color: #000; ">Hello world!</h4>
</div>

to add the html2canvas script and a div that we want to capture and download as an image.

Then we write:

(async () => {
  const canvas = await html2canvas(document.querySelector("#capture"))
  const link = document.createElement("a");
  link.download = 'capture.png';
  link.href = canvas.toDataURL("image/png");
  link.click();
  link.remove()
})()

to put the div content into a canvas and return it as a promise with html2canvas.

Then we create a link with createElement.

We set the file name of the downloaded file by setting the download propert.

Next, we set the URL of the file to download to the image with canvas.toDataURL.

And then we call click to start the download.

Finally, we call remove to remove the link.

Conclusion

To generate an image of a div and save the image to disk with JavaScript, we can use the html2canvas library.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *