我正在尝试使用网络摄像头拍摄快照。我已经覆盖了一个矩形,当拍摄照片时,该矩形将成为裁剪区域。当我拍摄照片时,拍摄的图像会被放大。如何使图像与矩形内的区域相同? 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();
答案 0 :(得分:0)
我发现视频是640 x 480,所以我需要找到比率
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);