MDN文档 - getUserMedia介绍
![](https://img2022.cnblogs.com/blog/1987782/202210/1987782-20221030161158424-295248638.png)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>camera</title>
</head>
<body>
<div id="contentHolder">
<video id="video" autoplay></video>
<img id="imgXX"/>
</div>
<button id="btn_snap" onclick="takePhoto()">拍照</button>
</body>
<script>
let width = height = video.width = video.height = 400;
const constraints = {
video: {
width,
height
}
}
navigator.mediaDevices.getUserMedia(constraints).then(stream => {
video.srcObject = stream;
video.onloadedmetadata = () => video.play();
})
// 拍照,这里借助canvas把video的一帧转换成图片
function takePhoto() {
let canvas = document.createElement('canvas');
canvas.width = canvas.height = 400;
const ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0, width, height);
document.getElementById('imgXX').src = canvas.toDataURL('image/png');
}
</script>
</html>