photo with distorted webcam using Html5 + javascript

Asked

Viewed 200 times

2

Using the code below, I can capture an image of the camera through the browser, but taking into account that I intend a Portrait format of 4x3 (354x472px). The way the measurements are indicated, the catch comes out in Landscape and the snapshot comes out 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>
  • the measurements are switched, is 472x354

  • @darkangel, would be switched if I want Landscape, but I want Portrait

1 answer

1


webcam only supports Landscape so you need 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.