How to take screenshot of a div with JavaScript

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.


The code for doing so will be −

 Live Demo

<!DOCTYPE html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
      height: 300px;
      width: 300px;
      display: flex;
      flex-direction: column;
      background-color: rgb(43, 216, 216);
      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); }
<script src=""></script>
   const download = () => {
      html2canvas(document.querySelector('#capture')).then(canvas => {
<div id='capture'>
<span id='first'>First Block</span>
<span id='second'>Second Block</span>
<span id='third'>Third Block</span>
<button onclick="download()">


And the output of the following code will be −


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.