1. 程式人生 > 其它 >VUE 中獲取攝像頭進行掃碼

VUE 中獲取攝像頭進行掃碼

前言:

最近專案中需要獲取攝像頭進行掃描二維碼、一維碼

參考文案:https://www.npmjs.com/package/@zxing/library

程式碼:

1、使用vue的npm 命令下載依賴

npm i @zxing/library --save

2、在需要使用的頁面上引用並建立

 import {BrowserMultiFormatReader} from '@zxing/library'
 export default {
     data() {
       return {
         codeReader: new BrowserMultiFormatReader(),
       }
     }
 }

3、呼叫攝像頭進行識別

that.codeReader.getVideoInputDevices().then((videoInputDevices) => {
          console.log('videoInputDevices', videoInputDevices);
          //檢視獲取到的攝像頭數量
      for (let i = 0; i < videoInputDevices.length; ++i) { let deviceInfo = videoInputDevices[i]; let option
= document.createElement('option'); option.value = deviceInfo.deviceId; if (deviceInfo.kind === 'videoinput') { option.text = deviceInfo.label; that.cameraNum.push(option) } else { // console.log('Found ome other kind of source/device: ', deviceInfo);
} } }).catch((err) => { that.$message.error('獲取攝像頭失敗:('); console.error(err); });

4、重置攝像頭

      //選擇攝像頭
      changPhoto(firstDeviceId){
        const that = this
        that.changPhotoId = firstDeviceId
        // 重置
        that.codeReader.reset()
        // 選擇攝像頭後進行識別that.codeReader.decodeFromInputVideoDeviceContinuously(firstDeviceId, 'video', (result, err) => {
          if (result) {
            console.log(result);
            //識別成功後進行停止識別(類似截圖)
            let video = document.getElementById('video');
            let canvas = document.getElementById('canvas');
            let context = canvas.getContext('2d');
            context.drawImage(video,0, 0, 240, 300);
            that.$createDialog().show()
          }
          if (err && !(err)) {
            console.error(err);
          }
        });
      },