1.關(guān)聯(lián)
在《初識html5使用jsQR識別二維碼》博文中我們已經(jīng)初步了解jsQR識別帶有QR碼的圖片。在現(xiàn)實環(huán)境中,我們常常使用手機掃碼QR,那么應(yīng)該怎樣解決呢??
2.解決方法
我們可以在手機瀏覽器的網(wǎng)頁上調(diào)用攝像頭,調(diào)用攝像頭使用核心的API navigator.mediaDevices.getUserMedia?提示用戶許可使用媒體輸入,媒體輸入會產(chǎn)生一個 MediaStream,里面包含了請求的媒體類型的軌道。
若用戶成功使用,它返回一個 Promise 對象,成功后會 resolve 回調(diào)一個 MediaStream對象;若用戶拒絕了使用權(quán)限,或者需要的媒體源不可用,promise 會 reject 回調(diào)一個 PermissionDeniedError 或者 NotFoundError 。
接著使用二維碼解析庫 JSQR掃描網(wǎng)絡(luò)攝像頭流,并將定位,提取和解析其中的任何 QR碼。
3.實現(xiàn)代碼
下面是實現(xiàn)的腳本
<script type="text/javascript">
var video = document.createElement("video");
var canvasElement = document.getElementById("canvas");
var canvas = canvasElement.getContext("2d");
// 描邊
function drawLine(begin, end, color) {
canvas.beginPath();
canvas.moveTo(begin.x, begin.y);
canvas.lineTo(end.x, end.y);
canvas.lineWidth = 4;
canvas.strokeStyle = color;
canvas.stroke();
}
// 嘗試打開手機上安裝后置攝像頭
navigator.mediaDevices.getUserMedia({
video: { facingMode: "environment" }
}).then(function (stream) {
video.srcObject = stream;
// 阻止IOS視頻全屏
video.setAttribute("playsinline", true);
video.play();
requestAnimationFrame(tick);
});
function tick() {
if (video.readyState === video.HAVE_ENOUGH_DATA) {
canvasElement.hidden = false;
canvasElement.height = video.videoHeight;
canvasElement.width = video.videoWidth;
canvas.drawImage(video, 0, 0, canvasElement.width, canvasElement.height);
var imageData = canvas.getImageData(0, 0, canvasElement.width, canvasElement.height);
// QR碼解析
var code = jsQR(
imageData.data, // 圖像數(shù)據(jù)
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");
alert(code.data);
}
}
requestAnimationFrame(tick);
}
</script>
4.發(fā)布到IIS
如下圖所示兩個文件:
?安裝下面方式新建站點,由于手機打開攝像頭需要安全連接,需要使用https,所以發(fā)布網(wǎng)站的時候,需要用https協(xié)議。
?5.效果圖
用手機打開網(wǎng)頁掃描圖片:
文章來源:http://www.zghlxwxcb.cn/news/detail-610752.html
例子下載文章來源地址http://www.zghlxwxcb.cn/news/detail-610752.html
到了這里,關(guān)于使用jsQR識別二維碼的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!