<body>
<video id="video" style="width: 400px"></video>
<canvas id="canvas" style="width: 400px"></canvas>
<br />
<button type="button" onclick="takePicture()">Take Picture</button>
<!-- https://cdn.jsdelivr.net/npm/jsqr@1.4.0/dist/jsQR.min.js -->
<script src="jsqr.js"></script>
<script>
function takePicture() {
navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' } }).then(
(stream) => {
/** @type {HTMLVideoElement} */
const video = document.getElementById('video');
/** @type {HTMLCanvasElement} */
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
video.muted = true;
video.setAttribute('playsinline', true);
video.onloadedmetadata = () => {
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
draw();
};
video.srcObject = stream;
video.play();
const draw = () => {
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
const { data } = ctx.getImageData(0, 0, canvas.width, canvas.height);
const code = jsQR(data, canvas.width, canvas.height);
video.requestVideoFrameCallback(() => {
console.log(code);
if (code) {
// 扫到二维码,停止视频流
video.pause();
video.srcObject.getTracks()[0].stop();
return;
}
draw();
});
};
},
(error) => {
console.error(error);
}
);
}
</script>
</body>
标签:扫码,code,const,canvas,height,width,video
From: https://www.cnblogs.com/chlai/p/18658440