5

In my web app I obtain a MediaStream either via getUserMedia or getDisplayMedia. In certain situations, the video track of that stream can change its size. For example, if getDisplayMedia tracks a specific window, that window can change size. Or on a mobile device, when switching from landscape into portrait mode, the camera image will be rotated by 90° (i.e. width and height get swapped).

I know how to get the dimensions of the MediaStream (as described here). I now want to get notified whenever the dimensions change. A callback/event of some sorts.

I already tried MediaStream.onaddtrack (guessing that maybe the track is removed and readded with a different size) and I also tried using a MutationObserver on the <video> element I am showing the stream in. None of these worked. I also checked MDN for other events that might help me, but I didn't find any promising ones.

Is there a way to subscribe to changes of a video track's dimension? A function of mine should be called each time the dimensions change. And if it's not possible and I would need to busy poll: is there a smart way how to make the polling a bit less busy?

Lukas Kalbertodt
  • 79,749
  • 26
  • 255
  • 305
  • If this is about a camera orientation, could you use the [orientationchange](https://developer.mozilla.org/en-US/docs/Web/API/Window/orientationchange_event) event? – mvr Feb 28 '20 at 10:51

1 Answers1

6

You can subscribe to resize event of your video element

const video = document.getElementById("video");

video.addEventListener("resize", (e) => {
  const { videoWidth, videoHeight } = video;
  // can do smth here
  // for example
  video.style.width = videoWidth;
  video.style.height = videoHeight;

}, false);
Firanolfind
  • 1,559
  • 2
  • 17
  • 36
  • Thanks! Do you know if there is a solution that does not require a ` – Lukas Kalbertodt Feb 28 '20 at 15:09
  • It works the same as with video tag. **htmlVideoElement** has also `.videoHeight`property. You will end up with video element in any case. `const stream = new MediaStream(); const video = document.createElement('video'); video.srcObject = stream;` – Firanolfind Mar 02 '20 at 08:49