简体   繁体   中英

HTML5 video webcam match resolution

I am trying to use the webcam to take a snapshot. I have overlayed a rectangle which will be the cropped area when the photo is taken. When I take the photo the image captured is zoomed in. How do I make the image the same as the area within the rectangle? https://jsfiddle.net/fzrLvbwf/9/

    var timer = null;
var timeto = 3; // time in seconds to capture
var video = document.getElementById('videoElement');

function handleVideo(stream) {
  video.src = window.URL.createObjectURL(stream);
}

function videoError(e) {

}

function init() {
  setUpCamera();

  // draw crop area box
  var c = document.getElementById("rectElement");
  var ctx = c.getContext("2d");
  c.width = 480;
  c.height = 360;
  ctx.lineWidth = "4";
  ctx.strokeStyle = "red";
  ctx.rect(120, 50, 240, 260);
  ctx.stroke();

  document.getElementById('btnPhoto').onclick = function() {

    var video = document.getElementById("videoElement");
    var canvas = document.getElementById('snapshot-canvas');
    var ctx = canvas.getContext('2d');
    var printImg = document.getElementById('print-img');

    canvas.width = 240;
    canvas.height = 260;

    // transform the canvas so the image matches the video horitontal flipped image
    ctx.translate(canvas.width, 0);
    ctx.scale(-1, 1);

    var x = (video.videoWidth - canvas.width) / 2;
    var y = (video.videoHeight - canvas.height) / 2;
    //ctx.drawImage(video, x, y, canvas.width, canvas.height, 0, 0, canvas.width, canvas.height);
    ctx.drawImage(video, 120, 50, 240, 260, 0, 0, 240, 260);

    var dataUrl = canvas.toDataURL('image/jpeg');
    printImg.src = dataUrl;

  }
}

function doPhoto() {

}

function setUpCamera() {
  navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia;

  if (navigator.getUserMedia) {
    navigator.getUserMedia({
      video: true
    }, handleVideo, videoError);

  }
}

init();

I found that the video was 640 x 480 so i needed to find the ratio

var rx = (video.videoWidth / videoContainer.clientWidth);
var ry = (video.videoHeight / videoContainer.clientHeight);

ctx.drawImage(video, 120 * rx, 50 * ry, 240 * rx, 260 * ry, 0, 0, 240, 260);

https://jsfiddle.net/fzrLvbwf/11/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM