How to use HTML5 canvas and JavaScript to take in-browser screenshots?

Spread the love

Sometimes, we want to use HTML5 canvas and JavaScript to take in-browser screenshots.

In this article, we’ll look at how to use HTML5 canvas and JavaScript to take in-browser screenshots.

How to use HTML5 canvas and JavaScript to take in-browser screenshots?

To use HTML5 canvas and JavaScript to take in-browser screenshots, we can use the navigator.mediaDevices.getDisplayMedia method.

For instance, we write

const stream = await navigator.mediaDevices.getDisplayMedia();
const track = stream.getVideoTracks()[0];
const capture = new ImageCapture(track);
const bitmap = await capture.grabFrame();
track.stop();

canvas.width = bitmap.width;
canvas.height = bitmap.height;
canvas.getContext("2d").drawImage(bitmap, 0, 0);

canvas.toBlob((blob) => {
  console.log("output blob:", blob);
});

to call navigator.mediaDevices.getDisplayMedia to get a promise with the stream.

Then we call stream.getVideoTracks to get the track.

Next we create an ImageCapture object to create the capture object.

And then we call capture.grabFrame to grab a screenshot.

Next, we draw the screenshot to the canvas with

canvas.width = bitmap.width;
canvas.height = bitmap.height;
canvas.getContext("2d").drawImage(bitmap, 0, 0);

And then we convert it to a blob with canvas.toBlob.

Conclusion

To use HTML5 canvas and JavaScript to take in-browser screenshots, we can use the navigator.mediaDevices.getDisplayMedia method.

Leave a Reply

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