Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rendering HTML5 Video to Canvas is squashing the image

I'm trying to take a photo from the user's webcam using getUserMedia.

The image from the camera is 640x480 (which presumably could be any size, depending on the user's webcam).

Ive got a video tag, sized to 320x240 with css, im im rendering the webcam image onto it like this:

var $video = $('video');
navigator.getUserMedia({ video: true }, function (stream) {
    $video[0].mozSrcObject = stream;
    $video[0].play();
    localMediaStream = stream;
}, function () {
    console.log('sadtrombone.com');
});

This works fine.

then, im taking a picture/still frame like this:

var ctx = $canvas[0].getContext('2d');
ctx.drawImage($video[0], 0, 0, $canvas[0].width, $canvas[0].height);

This draws the image onto the canvas, but it looks a bit blurry :/

then, if i do this:

$('img).attr('src', $canvas[0].toDataURL('image/png'));

this renders the canvas to an image element, but the image is squashed, its 300x150 :/

$canvas[0].width == 300 and $canvas[0].height == 150

Whats going on?

Update: Interestingly/strangely - if i do this instead:

ctx.drawImage($video[0], 0, 0, 320, 240);

i still end up with a 300x150 image, but its cropped. Although it does appear to be the correct aspect ratio from the source

Update 2: even stranger, if i do this:

ctx.drawImage($video[0], 0, 0, 640, 480);

i still end up with a 300x150 image, but its the top left quarter of the image :'(

like image 869
Andrew Bullock Avatar asked Dec 16 '22 14:12

Andrew Bullock


2 Answers

It would seem sizing the canvas with css is not enough. You have to do:

canvas.width = 320;
canvas.height = 240;

then

ctx.drawImage($video[0], 0, 0, 320, 240);

works corretly

like image 155
Andrew Bullock Avatar answered Dec 28 '22 23:12

Andrew Bullock


The canvas height and width can be set with the video height and width.

$canvas[0].height = $video[0].videoHeight;
$canvas[0].width = $video[0].videoWidth;
like image 20
ruffrey Avatar answered Dec 29 '22 00:12

ruffrey