Categories
JavaScript Answers

How to Take a Screenshot of a div with JavaScript?

Spread the love

Sometimes, we may 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.

Use the html2canvas Library

We can use the html2canvas library to capture the div as an image and put it into a canvas element.

To use it, we can add the library with a script tag by writing:

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

We can also install it with NPM by running:

npm install --save html2canvas

Or we can install it with Yarn by running:

yarn add html2canvas

Next, we can add the div we want to capture into an image by writing:

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

Then to select and capture the element, we can write:

const getScreenshotOfElement = async (element) => {
  const canvas = await html2canvas(element)
  document.body.appendChild(canvas)
}

const div = document.querySelector('div')
getScreenshotOfElement(div)

We have the getScreenOfElement function that takes the element we want to capture into an image and put into a canvas.

In the function, we just call the html2canvas function with the element .

This function returns a promise that resolves to a canvas element with the element converted to an image in the canvas.

Then we call document.body.appendChild with the canvas to append it to the body.

Next, we select the div with querySelector .

And then we call the getScreenOfElement function that we just created.

Now we should see the canvas with the image of our div displayed below the actual div.

Conclusion

We can use the html2canvas library to capture an element into an image inside a canvas element.

This lets us take a screenshot of an element easily.

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 *