How to Take Simple Screenshot in Vanilla JavaScript

To take a screenshot in vanilla JavaScript, you can use the html2canvas library. Here’s an example of how you can use it:

  1. First, include the html2canvas library in your HTML file:
Copy code<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
  1. Then, you can use the html2canvas function to generate a screenshot of an element on the page. For example, to take a screenshot of the body element:
Copy codehtml2canvas(document.body).then(function(canvas) {
  // canvas is a canvas element that contains the screenshot
});

You can also specify a specific element by passing its ID or a reference to the element itself:

Copy codehtml2canvas(document.getElementById('my-element')).then(function(canvas) {
  // canvas is a canvas element that contains the screenshot of the element with ID 'my-element'
});
  1. To save the screenshot as an image, you can use the toDataURL method of the canvas element to get a data URL representation of the image, and then set the src attribute of an img element to the data URL.
Copy codehtml2canvas(document.body).then(function(canvas) {
  var img = new Image();
  img.src = canvas.toDataURL();
  document.body.appendChild(img);
});

This will append an image element to the page with the screenshot as the source. You can also use the data URL to download the image or send it to a server.

Note that html2canvas only captures the visible portion of the page, so if the element you are trying to capture is not visible on the screen (e.g. because it is scrolled out of view), it will not be included in the screenshot.

Leave a Comment