photo with distorted webcam using html5 + javascript

2

Using the code below, I can capture a camera image through the browser, but taking into account that I want a 4x3 portrait format (354x472px). From the way the measurements are indicated, in the capture it leaves in landscape and in the snapshot it is distorted.

The code:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Documento sem título</title>
</head>

<body>
<video id="video" width="354" height="472" autoplay></video>
<button id="snap">Snap Photo</button>
<canvas id="canvas" width="354" height="472"></canvas>

<script>
// elementos, configurações, etc...
var video = document.getElementById('video');

// acesso à camera
if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
    navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) {
        video.src = window.URL.createObjectURL(stream);
        video.play();
    });
}

// snapshot
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var video = document.getElementById('video');

// trigger
document.getElementById("snap").addEventListener("click", function() {
    context.drawImage(video, 0, 0, 354, 472);
});
</script>
</body>
</html>
    
asked by anonymous 10.04.2018 / 19:58

1 answer

1

The webcam only supports landscape so you have to make a crop

<video id="video" width="630" height="472" autoplay></video>
<button id="snap">Snap Photo</button>
<canvas id="canvas" width="354" height="472"></canvas>

<script>
// elementos, configurações, etc...
var video = document.getElementById('video');

// acesso à camera
if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
    navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) {
        video.src = window.URL.createObjectURL(stream);
        video.play();
    });
}

// snapshot
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var video = document.getElementById('video');

// trigger
document.getElementById("snap").addEventListener("click", function() {
    var x = (630 - 354) / 2;
    context.drawImage(video, x, 0, 354, 472, 0, 0, 354, 472);
});
</script>
    
10.04.2018 / 21:02