我从用户的相机获取video
,并以1:1的方格显示。然后我有一个按钮拍摄照片并将其绘制到1:1画布,问题是它不是在画布上的相同位置绘制的。我怎样才能做到这一点?
这是一个正在运行的例子:
https://jsfiddle.net/90d3ar1m/
这是HTML:
<!doctype html>
<html>
<head>
<title>Camera</title>
<meta http-equiv="Content-Security-Policy" content="default-src * data: gap: https://ssl.gstatic.com 'unsafe-inline'; style-src * 'unsafe-eval'; media-src 'self' blob:">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/camera.css">
</head>
<body>
<div class="container">
<div class="camera">
<video id="monitor" autoplay></video>
</div>
<canvas id="photo"></canvas>
<input type=button value="📷" onclick="snapshot()">
</div>
<script type="text/javascript" src="js/plugins/jquery.min.js"></script>
<script type="text/javascript" src="js/dist/pages/camera.js"></script>
</body>
</html>
这是CSS:
video {
width: 500px;
height: 500px;
object-fit: cover;
object-position: center;
}
.camera {
width: 500px;
height: 500px;
overflow: hidden;
}
这是TypeScript:
let canvas: HTMLCanvasElement;
let video: HTMLVideoElement;
$(window).on('load', async event => {
video = <HTMLVideoElement>document.getElementById('monitor');
canvas = <HTMLCanvasElement>document.getElementById('photo');
video.srcObject = await navigator.mediaDevices.getUserMedia({ video: true });
video.onloadedmetadata = () => {
canvas.width = 500;
canvas.height = 500;
}
});
function snapshot() {
canvas.getContext('2d').drawImage(video, 0, 0);
}
答案 0 :(得分:1)
您的问题似乎是由于video
元素保持视频的宽高比而画布没有。还要记住,ctx.drawImage最多需要8个位置和大小参数:
context.drawImage(img/vid,sx,sy,swidth,sheight,x,y,width,height);
我做了一些测试,发现这个工作得很好,但你的里程可能会有所不同:
.drawImage(video,80,0,480,500,0,0,500,520);
我制作了jsFiddle with these numbers,请查看它是否适合您。
W3Schools有一些很好的文档说明这些是如何工作的,我建议阅读: http://www.w3schools.com/tags/canvas_drawimage.asp
您可以使用视频的videoWidth
和videoHeight
属性来计算drawImage
中针对不同宽高比源视频所需的数字