Why is ctx.drawImage only drawing part of the video element to the canvas?

I am trying to draw a movie frame onto a canvas element using ctx.DrawImage

and I get what I think is very strange scaling / cropping behavior.

First, here's my code:

Html

<body>
    <video autoplay width="125" height="125"></video>
    <img src="">
    <canvas></canvas>
</body>

      

JavaScript:

    var video = document.querySelector('video');
    var canvas = document.querySelector('canvas');
    var ctx = canvas.getContext('2d');
    var localMediaStream = null;

    function snapshot() {
        if (localMediaStream) {
            ctx.drawImage(video, 0, 0, 125, 125);
            document.querySelector('img').src = canvas.toDataURL('image/webp');
        }
    }   

video.addEventListener('click', snapshot, false);

navigator.getUserMedia(

    {
        video: true

    }, function(stream) {
        video.src = window.URL.createObjectURL(stream);
        localMediaStream = stream;
});

      

What this does is essentially take the still from the video and squish it so that it's about 1/3 of the original width and about 70% of the height. This is frustrating.

Leaving 125

and only using ctx.drawImage(video, 0, 0)

fills the canvas with a static one, however, it only touches the upper left corner (25%) of the image. It's also frustrating.

How can I make the canvas draw the image the same size as the video element?

This is because the video element itself is indeed 125px x 125px

, but mine because of the aspect ratio, there is a letter box (space) around the video element. Is there a way to make the video element fill the incoming video stream?

+3


source to share


2 answers


I used a webcam (with function navigator.getUserMedia

). The webcam resolution was significantly higher, and so even when the video element and canvas were the same dimensions, the captured image was much larger than it could have matched.



The solution was to add a property constrain

to make the media stream also125px x 125px

+1


source


I too faced the same problem when I tried ...

var sw = video.offsetWidth, // source width
    sh = video.offsetHeight, // source height
    dw = canvas.width, // destination width
    dh = canvas.height; // destination height
ctx.drawImage(video, 0, 0, sw, sh, 0, 0, dw, dh);

      

it was solved when i changed to:



ctx.drawImage(video, 0, 0, dw, dh);

      

I suppose in your case the problem is: 125

- height and width of the video element, but what you should supply is the height and width of the canvas, for example setting the width and height of the canvas:

canvas.width = 125;
canvas.height = 125;
ctx.drawImage(video, 0, 0, 125, 125);

      

+1


source







All Articles