Take Screenshots With Javascript (Simple Examples)

Welcome to a tutorial and examples on how to take screenshots with Javascript. So you have a project that needs to do screenshots? An easy way to capture screenshots in Javascript is to use the html2canvas library:

html2canvas(document.body).then(canvas => {
  let a = document.createElement("a");
  a.download = "ss.png";
  a.href = canvas.toDataURL("image/png");
  a.click();
});

That’s all for the “quick fix”, read on for detailed examples!

 

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

EXAMPLE CODE DOWNLOAD

Source code on GitHub Gist | Example on CodePen

Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

 

JAVASCRIPT SCREENSHOTS

All right, let us now get into the examples of how to take screenshots in Javascript.

 

TUTORIAL VIDEO

 

METHOD 1) USING HTML2CANVAS LIBRARY

1A) THE HTML

1a-html2canvas.html
<!-- (A) HTML2CANVAS LIBRARY -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<script src="1b-html2canvas.js"></script>
 
<h1>TEST</h1>
<textarea>Dummy Text - Change and see how it captures below!</textarea>
<input type="button" value="Capture" onclick="capture()">

Nothing much here actually. Just load the library and create some dummy elements to work with the screenshot.

 

1B) THE JAVASCRIPT

1b-html2canvas.js
function capture () {
  html2canvas(document.body).then(canvas => {
    let a = document.createElement("a");
    a.download = "ss.png";
    a.href = canvas.toDataURL("image/png");
    a.click(); // MAY NOT ALWAYS WORK!
  });
}

Yep, this is precisely the same snippet in the introduction. A couple of extra notes though:

  • Apart from canvas.toDataURL("image/png"), we can also set it to ("image/jpeg", QUALITY), or ("image/webp", QUALITY).
  • QUALITY is a number from 0 to 1, 0 being the lowest and 1 being the highest.
  • a.click() may not always work because of security restrictions. It is best to just append this link on the page, and let users manually click to save the screenshot.

 

 

METHOD 2) USING SCREEN CAPTURE API

2A) THE JAVASCRIPT

2b-media.js
async function capture () {
  // (A) GET MEDIA STREAM
  const stream = await navigator.mediaDevices.getDisplayMedia({
    preferCurrentTab: true
  });
 
  // (B) STREAM TO VIDEO
  const vid = document.createElement("video");
 
  // (C) VIDEO TO CANVAS
  vid.addEventListener("loadedmetadata", function () {
    // (C1) CAPTURE VIDEO FRAME ON CANVAS
    const canvas = document.createElement("canvas"),
          ctx = canvas.getContext("2d");
    ctx.canvas.width = vid.videoWidth;
    ctx.canvas.height = vid.videoHeight;
    ctx.drawImage(vid, 0, 0, vid.videoWidth, vid.videoHeight);

    // (C2) STOP MEDIA STREAM
    stream.getVideoTracks()[0].stop();

    // (C3) "FORCE DOWNLOAD"
    let a = document.createElement("a");
    a.download = "ss.png";
    a.href = canvas.toDataURL("image/png");
    a.click(); // MAY NOT ALWAYS WORK!
  });

  // (D) GO!
  vid.srcObject = stream;
  vid.play();
}

Javascript has a native screen capture API, but boy, it is confusing.

  • (A) This will ask for the user’s permission to share the current tab.
  • (B & D) Once we have a stream of the user’s current tab, feed it into a <video> tag.
  • (C1) From the <video>, we capture a single frame onto a <canvas>.
  • (C3) Then, “force download as image file” as usual.

 

2B) A COUPLE OF NOTES

  • getDisplayMedia will not work on all browsers at the time of writing – See compatibility checks below.
  • preferCurrentTab: true will only work on Chromium-based browsers; If this is not set, the current tab cannot be captured for some reason.
  • Although it is possible to specify video: { displaySurface: "window" } to capture the entire window instead.
  • Also, it is possible to record videos… Or even send the entire screen capture stream to the server.

 

 

EXTRAS

That’s all for this guide, and here is a small section on some extras and links that may be useful to you.

 

EXTRA) UPLOAD SCREENSHOT TO SERVER

JAVASCRIPT

3a-upload.js
// (A) APPEND SCREENSHOT TO DATA OBJECT
var data = new FormData();
data.append("screenshot", canvas.toDataURL("image/jpeg", 0.6));
 
// (B) UPLOAD SCREENSHOT TO SERVER
fetch("3b-upload.php", { method:"post", body:data })
.then(res => res.text())
.then(txt => alert(txt));

In both methods above, we can send the captured image to the server instead of forcing a download.

 

SERVER-SIDE SCRIPT

3b-upload.php
<?php
// https://netcell.netlify.com/blog/2016/04/image-base64.html
$file = fopen("screenshot.jpg", "w");
$data = explode(",", $_POST["screenshot"]);
$data = base64_decode($data[1]);
fwrite($file, $data);
fclose($file);
echo "OK";

On the server side, just save the uploaded image. This one is in PHP, but you can pretty much “translate” it to whatever other language you are using.

 

 

LINKS & REFERENCES

 

COMPATIBILITY CHECKS

These examples will work on any modern Grade A browser.

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *