代码:
// 获取访问摄像头的权限!
if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
// 不添加 `{ audio: true }`,因为我们现在只想要视频
navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) {
//video.src = window.URL.createObjectURL(stream);
video.srcObject = stream;
video.play();
});
}
// 获取页面上的div元素
const snapshotDiv = document.getElementById('snapshot');
// 获取摄像头画面的canvas元素
const canvas = document.createElement('canvas');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
// 将摄像头画面渲染到canvas上
const ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
// 将canvas转换为图片
const img = new Image();
img.src = canvas.toDataURL();
// 将图片渲染到页面上的div元素上
snapshotDiv.appendChild(img);