How to take screenshot of a div with JavaScript

JavascriptWeb DevelopmentFront End Technology

We are required to capture (convert into image) part(s) of our markup that lays out our website and save that captured image or do something with it. So, we are required to devise a way using which we can achieve this described behaviour.

As our problem includes capturing any markup element and not just canvas, it’s a bit complex and especially if we plan to do it from scratch. Therefore, for our ease we will use a third party library, htmltocanvas that does exactly what the name suggests, converting the desired markup to canvas, after which we can simply download the canvas element as an image.

Example

The code for doing so will be −

 Live Demo

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<style>
   #capture{
      height: 300px;
      width: 300px;
      display: flex;
      flex-direction: column;
      background-color: rgb(43, 216, 216);
   }
   span{
      flex: 1;
      width: 100%;
      display: flex;
      text-align: center;
      justify-content: center;
      align-items: center;
      color: #ffffff;
      font-size: 20px;
   }
   #first{ background-color: rgb(15, 168, 15); }
   #second{ background-color: rgb(43, 93, 228); }
   #third{ background-color: rgb(194, 55, 13); }
</style>
<body>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
<script>
   const download = () => {
      html2canvas(document.querySelector('#capture')).then(canvas => {
         document.body.appendChild(canvas);
      });
   }
</script>
<div id='capture'>
<span id='first'>First Block</span>
<span id='second'>Second Block</span>
<span id='third'>Third Block</span>
</div>
<button onclick="download()">
Download
</button>
</body>
</html>

Output

And the output of the following code will be −

AFTER CLICKING DOWNLOAD BUTTON

Note that the second image contains a canvas adjacent to the “Download” button, which we can simply right click and save to our local storage.

raja
Published on 22-Feb-2021 13:48:34
Advertisements