vue項目中實現H5調取攝像頭掃碼掃一掃功能+生成可識別的條形碼

vue項目中實現H5調取攝像頭掃碼掃一掃功能+生成可識別的條形碼

案例描述:需求是生成條形碼并且在vue項目中實現掃一掃功能并不是拍照上傳后端識別那種

項目場景:單純的h5項目,沒辦法調用微信等封裝好的組件或者js因為有些場景并不在微信自帶的瀏覽器里面

問題描述:

生成條形碼使用vue-barcode

cnpm i vue-barcode -D


//在main.js中
import VueBarcode from 'vue-barcode';

Vue.component('barcode', VueBarcode)
//在對應生成條形碼頁面
 <barcode :width="2" :value="code" :options="{format: 'CODE39', width: 2,displayValue: false}"></barcode>
 //value為輸入需要生成的code
 //value注意不要太長因為太長的話生成的碼也很長很密集,h5實現的掃一掃畢竟性能
 //不是很好太密集太長識別不了,如果java生成的碼出現掃不
 //出來的情況告訴他試試調整成Code-128

第一步:因為掃碼js不支持vue組件注冊或者是引入等方式,就算是支持我感覺也很麻煩,所以這樣的話以動態創建script的方法將掃碼js引入vue項目中

//動態創建script的方法
 AddJs: function (url) {
    console.log(url,'url')
    return new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.type = 'text/javascript'
      document.body.appendChild(script)
      script.onload = () => {
        resolve()
      }
    })
  },

第二步:在對應的vue頁面調用方法將掃碼js引入

 methods: {
     init(){
        util.loadJs('https://unpkg.com/html5-qrcode/minified/html5-qrcode.min.js')  
    },
 },
 mounted(){
    this.init()
  }

第三步:在對應的vue頁面中設置盛放掃碼的div盒子

<template>
 <div id="qr-reader" style="width:100%;height: 100%;"></div>
<template>

第四步:獲取當前設備的攝像頭列表id并存儲為接下來使用

getCameras(){
        Html5Qrcode.getCameras().then(devices => {
        //判斷有沒有設備的攝像頭列表
          if (devices && devices.length) {
             // devices 是設備的攝像頭列表如果大于1的話默認取后面攝像頭
              if(devices.length>1){
                this.cameraId = devices[1].id;
              }else{
                this.cameraId = devices[0].id;
              } 
          }
        }).catch(err => {
          // handle err
        });
    }

第五步:拿存儲的設備的攝像頭列表id啟動掃碼

start(){
        this.html5QrCode = new Html5Qrcode('qr-reader')
        this.html5QrCode.start(
          this.cameraId,     // 上面獲取到的id
          {
            fps: 10,    // sets the framerate to 10 frame per second
            qrbox: 250  // sets only 250 X 250 region of viewfinder to
                        // scannable, rest shaded.
          },
          qrCodeMessage => {
            // do something when code is read. For example:
            if(qrCodeMessage){
                 //成功掃出碼qrCodeMessage為掃碼內容
                 //掃碼成功記得關掉攝像
                 this.stop()
            }
           
          },
          errorMessage => {
            // parse error, ideally ignore it. For example:
            // console.log(`QR Code no longer in front of camera.`);
          })
        .catch(err => {
          // Start failed, handle it. For example,
          console.log(`Unable to start scanning, error: ${err}`);
        });
    },

第六步:關掉攝像頭

stop(){
        this.html5QrCode.stop().then(ignore => {
          // QR Code scanning is stopped.
          console.log("QR Code scanning stopped.");
        }).catch(err => {
          // Stop failed, handle it.
          console.log("Unable to stop scanning.");
        });
    },

總體頁面:

使用vue實現h5掃碼功能

<template>
 <div class="scan">
     
     <div class="sectionview">
         <div id="qr-reader" style="width:100%;height: 100%;"></div>
     </div>
    
    <div class="footer">
    <van-button @click="getCameras" color="rgba(249, 185, 73, 1)">Obtain Access</van-button>
    </div>
 </div>
</template>
 
<script >
import util from '../common/js/util.js'
 export default {
 data() {
  return {
  codeUrl: '',
  cameraId:''
  }
 },
 beforeDestroy(){
     this.stop()
 },
 methods: {
   getCode(id){
      //跳轉頁面
   },
   init(){
        util.loadJs('https://unpkg.com/html5-qrcode/minified/html5-qrcode.min.js')
        //需要加載時間建議延時一點再獲取設備列表
        setTimeout(()=>{
            this.getCameras()
        },1000)
        
        
    },
    stop(){
        this.html5QrCode.stop().then(ignore => {
          // QR Code scanning is stopped.
          console.log("QR Code scanning stopped.");
        }).catch(err => {
          // Stop failed, handle it.
          console.log("Unable to stop scanning.");
        });
    },
    start(){
        this.html5QrCode = new Html5Qrcode('qr-reader')
        this.html5QrCode.start(
          this.cameraId,     // retreived in the previous step.
          {
            fps: 10,    // sets the framerate to 10 frame per second
            qrbox: 250  // sets only 250 X 250 region of viewfinder to
                        // scannable, rest shaded.
          },
          qrCodeMessage => {
            // do something when code is read. For example:
            if(qrCodeMessage){
                 this.getCode(qrCodeMessage)
                 this.stop()
            }
           
          },
          errorMessage => {
            // parse error, ideally ignore it. For example:
            // console.log(`QR Code no longer in front of camera.`);
          })
        .catch(err => {
          // Start failed, handle it. For example,
          console.log(`Unable to start scanning, error: ${err}`);
        });
    },
    getCameras(){
        Html5Qrcode.getCameras().then(devices => {
          /**
           * devices would be an array of objects of type:
           * { id: "id", label: "label" }
           */
          if (devices && devices.length) {
              if(devices.length>1){
                this.cameraId = devices[1].id;
              }else{
                this.cameraId = devices[0].id;
              }
          
            
            console.log(this.cameraId,'cameraId')
            this.start()
            // .. use this to start scanning.
          }
        }).catch(err => {
          // handle err
        });
    }
    
    
  },
  mounted(){
    this.init()
  }

 }
</script>
<style lang="less">
 .scan {
    width: 100%;
    display: flex;
    flex-direction: column;
    height:100vh;
    overflow: hidden;
    .footer{
        width: 100%;
        display: flex;
        justify-content: center;
    }
    
    
 }
</style>

后期優化改善研究參考文檔

如果對你有用不要忘記點贊收藏哦!
https://github.com/mebjas/html5-qrcode

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。