irredev irredev - 3 days ago 5
Javascript Question

How to get original image from webcam in js?

How can I get the webcam video on the left to be in the same format as the right where the image is drawn?

Had this problem for a while and can't figure it out!

enter image description here

here's the code:

document.getElementById('capture').addEventListener('click', function() {
var w = video.videoWidth;
var h = video.videoHeight;
canvas.width = w;
canvas.height = h;
context.drawImage(video,0,0,w,h);
canvas.style.display='block';

});

Answer

video.videoWidth is not the real width of video so you get different ratio on new canvas. Try this:

var videoRatio = video.videoWidth / video.videoHeight;
var width = video.offsetWidth, height = video.offsetHeight;
var elementRatio = width/height;
if(elementRatio > videoRatio) width = height * videoRatio;
else height = width / videoRatio;

canvas.width = width;
canvas.height = height;
context.drawImage(video,0,0,width,height);
canvas.style.display='block';
Comments