JS調用本地USB攝像頭&獲取截圖
<!doctype html>
<html lang="en">
<head>
<title>GET VIDEO</title>
<meta charset="utf-8">
</head>
<body>
<input type="button" title="開啓攝像頭" value="開啓攝像頭" onclick="getMedia()" />
<video id="video" width="500px" height="500px" autoplay="autoplay"></video>
<canvas id="canvas" width="500px" height="500px"></canvas>
<button id="snap" onclick="takePhoto()">拍照</button>
<script>
let video = document.getElementById("video");
function getMedia() {
let constraints = {
video: {width: 500, height: 500},
audio: true
};
let promise = navigator.mediaDevices.getUserMedia(constraints);
promise.then(function (MediaStream) {
video.srcObject = MediaStream;
video.play();
}).catch(function (PermissionDeniedError) {
console.log(PermissionDeniedError);
})
}
function takePhoto() {
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0, 500, 500);
}
</script>
</body>
</html>