irredev irredev - 1 month ago 12
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;



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;