- 我也是第一次做html5調(diào)用攝像頭識(shí)別二維碼這種,那就廢話不多說開始吧
經(jīng)過各種查閱發(fā)現(xiàn)了一個(gè)純前端的解析二維碼的一個(gè)依賴jsqr,感謝jsqr的支持. - 這個(gè)是直接在canvas中畫出的攝像頭video,因?yàn)槲覜]有查到如何直接封裝拍照 (手動(dòng)狗頭一下)
<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>
- 重要的地方來了 主要就是這三個(gè)方法
//獲取navigator 瀏覽器所有插件元素 調(diào)用攝像頭 然后調(diào)用 requestAnimationFrame()方法,學(xué)過three就應(yīng)該知道的
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進(jìn)行解析如果解析出來就用canvas畫上線然后在跳轉(zhuǎn)至需要的頁面
//這里可以根據(jù)自己的需求改
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);
},
//這個(gè)就是canvas的函數(shù)了
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源碼 如果有幫助的話點(diǎn)一個(gè)star吧,謝謝??