web/html5。 Vue識(shí)別二維碼進(jìn)行跳轉(zhuǎn)

  • 我也是第一次做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吧,謝謝??

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容