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?
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?
Share Improve this question asked Feb 25, 2020 at 17:17 Lukas KalbertodtLukas Kalbertodt 89.4k32 gold badges274 silver badges334 bronze badges 1- If this is about a camera orientation, could you use the orientationchange event? – mvr Commented Feb 28, 2020 at 10:51
1 Answer
Reset to default 8 +100You 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);