html 异步加载jsQR.js 实例
时间: 2023-11-30 16:03:12 浏览: 148
jsQR.js框架读取二维码
以下是一个使用HTML异步加载jsQR.js的示例:
```html
<!DOCTYPE html>
<html>
<head>
<title>异步加载jsQR.js示例</title>
</head>
<body>
<h1>使用jsQR.js解码二维码</h1>
<canvas id="canvas" width="300" height="300"></canvas>
<div id="result"></div>
<script>
function loadScript(url, callback) {
var script = document.createElement("script");
script.type = "text/javascript";
if (script.readyState) { // IE
script.onreadystatechange = function() {
if (script.readyState == "loaded" || script.readyState == "complete") {
script.onreadystatechange = null;
callback();
}
};
} else { // Others
script.onload = function() {
callback();
};
}
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
// 异步加载jsQR.js
loadScript("https://cdn.jsdelivr.net/npm/jsqr@2.0.4/dist/jsQR.min.js", function() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var resultDiv = document.getElementById("result");
// 获取摄像头或文件上传的图片
navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) {
// 摄像头
var video = document.createElement("video");
video.srcObject = stream;
video.play();
// 每隔200ms检测一次
setInterval(function() {
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
var code = jsQR(imageData.data, imageData.width, imageData.height);
if (code) {
resultDiv.innerHTML = "二维码内容是:" + code.data;
}
}, 200);
}).catch(function(error) {
// 文件上传的图片
var img = new Image();
img.src = "qrcode.png";
img.onload = function() {
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
var code = jsQR(imageData.data, imageData.width, imageData.height);
if (code) {
resultDiv.innerHTML = "二维码内容是:" + code.data;
}
};
});
});
</script>
</body>
</html>
```
在上面的示例中,我们使用了`loadScript`函数来异步加载`jsQR.js`。在加载完成后,我们使用`jsQR`函数来解码二维码,并在页面上显示结果。我们还使用了`getUserMedia`函数来获取摄像头的视频流,并每隔200ms检测一次,以便在摄像头中检测到二维码时及时显示结果。如果使用的是文件上传的图片,则直接在图片加载完成后检测二维码并显示结果。
阅读全文