- 我也是第一次做html5調用攝像頭識別二維碼這種,那就廢話不多說開始吧
經過各種查閱發現了一個純前端的解析二維碼的一個依賴jsqr,感謝jsqr的支持. - 這個是直接在canvas中畫出的攝像頭video,因為我沒有查到如何直接封裝拍照 (手動狗頭一下)
<template>
<div class="v-body">
<canvas :width="canvasWidth"
:height="canvasHeight"
id="canvas"
v-show="showCanvas"
ref="canvasElement"></canvas>
<img :src="sys"
@click="openScan"
class="btn-sys" />
</div>
</template>
- 重要的地方來了 主要就是這三個方法
//獲取navigator 瀏覽器所有插件元素 調用攝像頭 然后調用 requestAnimationFrame()方法,學過three就應該知道的
openScan() {
const videoParam={ video: { facingMode: { exact: 'environment' } } };
navigator.mediaDevices.getUserMedia(videoParam).then((stream) => {
this.video.srcObject=stream;
this.video.setAttribute('playsinline',true);
this.video.play();
requestAnimationFrame(this.tick); r1
});
},
//這里是截取canvas中的圖形然后用jsqr進行解析如果解析出來就用canvas畫上線然后在跳轉至需要的頁面
//這里可以根據自己的需求改
tick() {
if(this.video.readyState===this.video.HAVE_ENOUGH_DATA) {
this.showCanvas=true;
this.canvasHeight=this.video.videoHeight;
this.canvasWidth=this.video.videoWidth;
!this.canvas2d&&(this.canvas2d=this.$refs.canvasElement.getContext('2d'));
this.canvas2d.drawImage(this.video,0,0,this.canvasWidth,this.canvasHeight);
var imageData=this.canvas2d.getImageData(0,0,this.canvasWidth,this.canvasHeight);
var code=jsQR(imageData.data,imageData.width,imageData.height,{
inversionAttempts: 'dontInvert'
});
if(code) {
this.drawLine(code.location.topLeftCorner,code.location.topRightCorner,'#FF3B58');
this.drawLine(code.location.topRightCorner,code.location.bottomRightCorner,'#FF3B58');
this.drawLine(code.location.bottomRightCorner,code.location.bottomLeftCorner,'#FF3B58');
this.drawLine(code.location.bottomLeftCorner,code.location.topLeftCorner,'#FF3B58');
this.outputData=code.data;
window.location.href=this.outputData
} else {
this.outputData=undefined;
}
}
requestAnimationFrame(this.tick);
},
//這個就是canvas的函數了
drawLine(begin,end,color) {
this.canvas2d.beginPath();
this.canvas2d.moveTo(begin.x,begin.y);
this.canvas2d.lineTo(end.x,end.y);
this.canvas2d.lineWidth=4;
this.canvas2d.strokeStyle=color;
this.canvas2d.stroke();
}
附上github源碼 如果有幫助的話點一個star吧,謝謝??