3

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!

T.Demirer
  • 118
  • 9

1 Answers1

1

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.

RickN
  • 12,537
  • 4
  • 24
  • 28
  • thank you. Can we use this for any div or iframe, or will it only work with a video object? Also, does the user agent request permission first before we do this? – smartblonde Aug 08 '21 at 17:26
  • All user agents require the user to first allow desktop screen capture. In fact, on Mac OS, the user might even need to whitelist their _browser_ in System Preferences even before allowing the _webpage itself!_ Capturing a `
    ` or `
    – RickN Aug 10 '21 at 10:13
  • Yes, you are right. It is a royal PITA though that we have to request permission every time, even for the same element, especially since it is coming from a user gesture. – smartblonde Aug 11 '21 at 01:20