I am trying to take a snapshot of a video feed from a webcam. The preview works fine, but when I try to capture it and turn it into a picture only a very small part of it is captured. A 320x150 part of the right top corner.
Already tried:
CSS:
canvas
{
display: none;
position:fixed;
top: 0;
left:0;
width: 100%;
height: 100%;
}
video
{
height:100%;
width:100%;
object-fit:cover;
}
Javascript:
var constraints = {
video: {width: {exact: 1280}, height: {exact: 720}}
};
navigator.mediaDevices.getUserMedia(constraints).then((stream) => { video.srcObject = stream; });
function take_snapshot(type)
{
var v = video.videoWidth;
var h = video.videoHeight;
console.log("width =" +v+ "height= "+h );
//This shows 1200x720
canvas.style.width = v;
canvas.style.height = h;
canvas.getContext('2d').drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
let image_data_url = canvas.toDataURL('image/jpeg');
console.log(image_data_url);
// data url of the image
var http = new XMLHttpRequest();
var url = 'save.php';
var params = 'image='+image_data_url;
http.open('POST', url, true);
//Send the proper header information along with the request
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
}
HTML:
<div id ="cameraContainer">
<div id="camera">
<video autoplay="true" id="cameraPreview"></video>
<div id="overlay">
<img id="overlayImage" src="">
</div>
</div>
<div id="buttonContainer">
<div id="button">
<button id="pictureButton" class="btn btn-success btn-block">Maak Foto</button>
</div>
</div>
</div>
</div>
<canvas id="canvas"></canvas>
The image is the same, when saved or displayed. The data image url is also very short (just 1-20kb). Videoheight and width are correct, so the issue seems to be somewhere in the capture function.
Any help would be appreciated.
You need to set the size of the actual canvas, like this:
canvas.width = v;
canvas.height = h;
canvas.style.width = v;
canvas.style.height = h;
Just changing the style width/height doesn't make the canvas bigger. When a canvas isn't given an explicit width and height in pixels it gets, according to the MDN documentation, a default width of 300 x 150. It's not hard to believe a browser used a default of 320 x 150 instead, though.