【HTML】基于jsQR实现的HTML单页面扫码功能
<!DOCTYPE html>
<html>
<head>
<title>扫一扫</title>
<script src="https://cdn.jsdelivr.net/npm/jsqr@latest/dist/jsQR.js"></script>
<style>
#qr-canvas {
width: 300px;
height: 200px;
}
</style>
</head>
<body>
<video id="qr-video" width="300" height="200" autoplay></video>
<canvas id="qr-canvas" width="300" height="200"></canvas>
<script>
const video = document.createElement("video");
const canvasElement = document.getElementById("qr-canvas");
const canvas = canvasElement.getContext("2d");
let scanning = false;
video.setAttribute("autoplay", "");
const mediaStreamTrack = typeof video.srcObject !== "undefined" ? video.srcObject : video.mozSrcObject;
const scan = () => {
if (mediaStreamTrack === null || mediaStreamTrack === undefined) {
throw new Error("Media stream error");
}
canvasElement.width = video.videoWidth;
canvasElement.height = video.videoHeight;
canvas.drawImage(video, 0, 0, canvasElement.width, canvasElement.height);
const imageData = canvas.getImageData(0, 0, canvasElement.width, canvasElement.height);
const code = jsQR(imageData.data, imageData.width, imageData.height, {
inversionAttempts: "dontInvert",
});
if (code) {
console.log("扫描结果:", code.data);
scanning = false;
}
};
video.srcObject = mediaStreamTrack;
video.onloadedmetadata = () => {
video.play();
scanning = true;
};
setInterval(() => {
if (scanning) {
scan();
}
}, 100);
</script>
</body>
</html>
这段代码使用了HTML5的<video>
标签和Canvas API来实现视频流的捕获和二维码的扫描。它首先创建了一个video
元素,并通过Canvas API将视频流转换成图像,然后使用jsQR
库来解析图像中的二维码。扫描结果会输出到控制台。这个例子简洁明了,并且注重于实现核心功能,非常适合作为初学者学习和实践的示例。
评论已关闭