0

I get live video from the webcam and, in order to fit a div with width/height that I want, the best solution I found was use object-fit: cover like this:

<video id="videoId" style='object-fit: cover;' autoplay="true" playsInline></video>
<img id="myImage" src="">    

The problem arises when I try to get the EXACT bitmap content of that video, using

var video     = document.getElementById('videoId');
var canvas    = document.createElement("canvas");
canvas.width  = video.width;
canvas.height = video.height;

canvas.getContext('2d').drawImage(video, 0, 0, video.width, video.height);
document.getElementById('myImage').src = canvas.toDataURL();

I do not get the video content, but the "real" video stream, which is different because I am using the object-fit: cover style.
Is there a way to grab a screenshot so to speak of that video? In theory, I could play with width/height offsets because "in theory" I know the original resolution of the video, but when I tried, it became messy. DPI, pixels, zoom...

Thank you

ZioBit
  • 905
  • 10
  • 29
  • Perhaps you can put that "real" `imagedata` into an `` element that also has `object-fit:cover`, then it will look the same again. Depends on what your purpose is! Otherwise you will have to calculate manually what `cover` does. That means scaling by aspect ratio (width/height) based on the largest of those two. – Kokodoko Jun 19 '21 at 13:19
  • Thank you, I will try it. My purpose it to literally "take a screenshot" of whatever is there in the video element, but if (as described) I simply get the canvas of the video element, then it is NOT what is displayed due to the object-fit:cover – ZioBit Jun 20 '21 at 04:39
  • I wrote [this answer](https://stackoverflow.com/a/34429774/3702797) a long time ago from which you can grab the "xMidYMid slice" behavior (it's the same as object-fit: cover + object-position: center). https://jsfiddle.net/xh3npwoc/ I unfortunately miss the time to make the logic simpler and more self explanatory... (also note that for presentation only, can also have this object-fit rule, but it won't affect its underlying bitmap). – Kaiido Jun 20 '21 at 09:13
  • I think `object:fit` is just `scale:(height/width)` - as long as the width is larger than the height. (if you want `object:cover` you do `scale(width/height)`. So you could apply that to the bitmap data of the video before you draw it on the canvas. – Kokodoko Jun 21 '21 at 09:14
  • No it's not just scaling by height, you need to find if it should be scaled by height or by width depending on both the input size and the output one. – Kaiido Jun 21 '21 at 09:17
  • True, but most videos are 16:9. If it is a vertical video, you can reverse width and height :) – Kokodoko Jun 21 '21 at 09:18
  • Even if we can assume that the input is in portrait, we can't assume how the output is, so it's still not "just scaling by " something. – Kaiido Jun 21 '21 at 09:21

0 Answers0