为什么当我尝试使用网络摄像头拍照时,只捕获了一小部分流?

Why is only a small part of the stream captured when I try to take a picture with the webcam?

我正在尝试从网络摄像头拍摄视频源的快照。预览效果很好,但是当我尝试捕获它并将其转换为图片时,只捕获了很小的一部分。右上角的 320x150 部分。

已经尝试过:

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)。 Videoheight 和 width 是正确的,所以问题似乎出在捕获功能的某个地方。

如有任何帮助,我们将不胜感激。

您需要设置实际大小canvas,像这样:

    canvas.width = v;
    canvas.height = h;
    canvas.style.width = v;
    canvas.style.height = h;

仅仅改变样式 width/height 不会使 canvas 变大。当 canvas 没有给出明确的宽度和高度(以像素为单位)时,它会得到 according to the MDN documentation, a default width of 300 x 150。不过,不难相信浏览器使用的是默认值 320 x 150。