1.navigator.mediaDevices.getUserMedia调用摄像头
2.canvas获取摄像头图像
3.强大的jsQR.js框架进行图像分析,并返回json结果
(见我的资源)
4.递归调用requestAnimationFrame(), 约每1/60秒执行一次
5.内容去重
<!doctype html>
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>二维码解析器</title>
<script src="./js/jsQR.js"></script>
</head>
<body>
<center><h1>二维码解析器</h1>
<div id="loadingMessage" hidden="">⌛ Loading video...</div>
<canvas id="canvas"></canvas>
<div id="outputMessage">暂时没有检测到二维码!</div>
</div>
</center>
</body>
</html>
<script>
var time = new Date();
var video = document.createElement("video");
var canvas = document.getElementById("canvas");
var pen = canvas.getContext("2d");
var loadingMessage = document.getElementById("loadingMessage");
var outputMessage = document.getElementById("outputMessage");
var strTemp = "";
function drawLine(begin, end, color) {
pen.beginPath();
pen.moveTo(begin.x, begin.y);
pen.lineTo(end.x, end.y);
pen.lineWidth = 4;
pen.strokeStyle = color;
pen.stroke();
}
navigator.mediaDevices.getUserMedia({
video: {
width:500,
height:330,
facingMode: "environment"
}
}).then(function(stream) {
video.srcObject = stream;
video.play();
requestAnimationFrame(tick);
});
function getNow() {
time = new Date();
return time.toLocaleString();
}
function tick() {
loadingMessage.innerText = "⌛ Loading video..."
if(video.readyState === video.HAVE_ENOUGH_DATA) {
loadingMessage.hidden = true;
canvas.height = video.videoHeight;
canvas.width = video.videoWidth;
pen.drawImage(video, 0, 0, canvas.width, canvas.height);
var imageData = pen.getImageData(0, 0, canvas.width, canvas.height);
var code = jsQR(imageData.data, imageData.width, imageData.height, {
inversionAttempts: "dontInvert",
});
if(code) {
drawLine(code.location.topLeftCorner, code.location.topRightCorner, "#FF3B58");
drawLine(code.location.topRightCorner, code.location.bottomRightCorner, "#FF3B58");
drawLine(code.location.bottomRightCorner, code.location.bottomLeftCorner, "#FF3B58");
drawLine(code.location.bottomLeftCorner, code.location.topLeftCorner, "#FF3B58");
if(strTemp != code.data) {
outputMessage.innerHTML = getNow() + "_" + code.data;
strTemp = code.data;
}
}
}
requestAnimationFrame(tick);
}
</script>