前端启动摄像头的API

时间:2022-01-13 03:48:45

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<video autoplay></video>
<button>Snap Photo</button>
<canvas></canvas>
<script type="text/javascript">
window.onload = function(){
var canvas = document.getElementById(‘canvas‘);
var context = canvas.getContext(‘2d‘);
var video = document.getElementById(‘video‘);
// Get access to the camera!
if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
// Not adding `{ audio: true }` since we only want video now
navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) {
video.src = window.URL.createObjectURL(stream);
video.play();
});
}

document.getElementById("snap").addEventListener("click", function() {
context.drawImage(video, 0, 0, 640, 480);
});
}
</script>
</body>
</html>