4

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 :'(

Andrew Bullock
  • 35,549
  • 33
  • 151
  • 228

2 Answers2

11

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

Andrew Bullock
  • 35,549
  • 33
  • 151
  • 228
  • 2
    Yep. Intrinsic width of `canvas` is 300x150. Changing the size with CSS doesn't change the intrinsic resolution, same as changing the size of a PNG or JPG with CSS doesn't change intrinsic resolution of the images. http://stackoverflow.com/q/5034529/8655 – robertc Feb 11 '13 at 22:07
  • the last 2 parameter did it for me – Nick Chan Abdullah Jan 31 '21 at 12:29
1

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;
ruffrey
  • 5,579
  • 3
  • 21
  • 19