参考极客时间做了一个拍照的demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<style>
* {
margin: 0;
padding: 0
}
canvas {
margin: 40px auto;
}
</style>
</head>
<body>
<video autoplay playsinline></video>
<canvas width="600" height="450"></canvas>
<button>拍照</button>
<button>下载</button>
<script>
'use strict';
var canvas = document.getElementsByTagName('canvas')[0];
var ctx = canvas.getContext('2d');
var btn = document.getElementsByTagName('button')
function draw() {
ctx.drawImage(localVideo, 0, 0, canvas.width, canvas.height)
}
function download() {
var url = canvas.toDataURL("image/jpeg")
var a = document.createElement('a');
document.body.appendChild(a)
a.href = url;
a.download = 'picture';
a.click()
document.body.removeChild(a)
}
btn[0].onclick = function () {
draw()
}
btn[1].onclick = function () {
download()
}
const mediaStreamContrains = {
video: true
};
const localVideo = document.querySelector('video');
function gotLocalMediaStream(mediaStream) {
localVideo.srcObject = mediaStream;
}
function handleLocalMediaStreamError(error) {
console.log('navigator.getUserMedia error: ', error);
}
navigator.mediaDevices.getUserMedia(mediaStreamContrains).then(
gotLocalMediaStream
).catch(
handleLocalMediaStreamError
);
</script>
</body>
</html>
navigator.mediaDevices.getUserMedia(constraints)方法返回一个promise对象,constraints是一个对象,可以设置视频,音频的属性,然后把返回的六对象赋值给video标签的srcObject即可显示图像,再调用canvas绘制图像及生成url即可下载图片