Categories
JavaScript Answers

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 use the getDisplayMedia method.

For instance, we write

<video style="width: 100%; height: 100%; border: 1px black solid" />

to add a video element.

Then we write

const mediaStream = await navigator.mediaDevices.getDisplayMedia();
const video = document.querySelector("video");
video.srcObject = mediaStream;
video.onloadedmetadata = (e) => {
  video.play();
  video.pause();
};

to call getDisplayMedia to get permission for using the display.

Then we select the video element with querySelector.

And then we set the srcObject to the mediaStream that we get after permission is granted.

Then we set onloadedmetadata to a function that calls play to play the video and pause to pause it once the display is captured.

Conclusion

To use HTML5 Canvas and JavaScript to take in-browser screenshots, we use the getDisplayMedia method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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