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);
          }
        });
      },    
上一篇:JUnit 5系列之架构体系介绍


下一篇:一款基于Uniapp开发的开源低代码平台