How to capture div into image using html2canvas?

Sometimes, we want to capture div into image using html2canvas.

In this article, we’ll look at how to capture div into image using html2canvas.

How to capture div into image using html2canvas?

To capture div into image using html2canvas, we can use the html2canvas function to return a promise with the canvas with the captured element content.

For instance, we write:

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.3.2/html2canvas.min.js">
</script>

<div id='hello'>
  hello world
</div>

to add a div.

Then we write:

(async () => {
  const div = document.getElementById('hello')
  const canvas = await html2canvas(div)
  document.body.appendChild(canvas)
})()

We select the div with document.getElementById.

Then we call html2canvas with div to capture the div’s content into a canvas.

And finally, we call document.body.appendChild with canvas to attach the captured canvas into the body.

Now we should see an image version of the div displayed.

Conclusion

To capture div into image using html2canvas, we can use the html2canvas function to return a promise with the canvas with the captured element content.