我正在尝试从网络摄像头拍摄视频源的快照。预览效果很好,但当我试图捕捉它并将其转换为图片时,只捕捉到它的一小部分。右上角的320x150部分。
已尝试:
- 更改CSS显示属性
- 将画布宽度和高度设置为视频高度(显示1200x720,所以这是正确的
- 更改画布的位置
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>
保存或显示时,图像是相同的。数据图像url也很短(只有1-20kb(。视频高度和宽度是正确的,所以问题似乎在捕获功能中。
如有任何帮助,我们将不胜感激。
您需要设置实际画布的大小,如下所示:
canvas.width = v;
canvas.height = h;
canvas.style.width = v;
canvas.style.height = h;
仅仅更改样式宽度/高度并不会使画布变大。根据MDN文档,当画布没有以像素为单位的明确宽度和高度时,默认宽度为300 x 150。不过,不难相信浏览器使用了默认的320 x 150。