Can I capture a single HTML div via getDisplayMedia?

Viewed 565

I was working on screen capture API and created some little projects about this. My question is, can I capture a custom HTML div instead of capturing tabs, windows or screens?

This is the code part that I used for capturing screen.

    captureStream = await navigator.mediaDevices.getDisplayMedia();
    const video = document.createElement("video");
    video.id = "vid";
    addVideoStream(video, captureStream);

Thanks!

1 Answers

I don't believe there's an option for this, but I think you can achieve this by doing:

  1. Get the video stream
  2. Get the position and dimensions of the element in the DOM.
  3. Render only a part of the video to a <canvas>, cropped to the values from step 1 & 2: ctx.drawImage(video, domX, domY, domWidth, domHeight, 0, 0, domWidth, domHeight);

You should be able to use pixel values but calculating the values in percentages may have an advantage in case the video stream is downsampled, although I don't think any browser does that.

You'll need to communicate to the user how to select the proper tab to capture. If you expect them to capture your web page but they wind up capturing the entire screen or a different tab, you'll get unexpected results.

Related