vue实现相机扫码功能

<template>
  <div>
    <button @click="scanCode">扫码</button>
  </div>
</template>

<script>
export default {
  methods: {
    scanCode() {
      console.log("浏览器信息", navigator.userAgent);
      this.$router.push({
        path: "/scanCodePage",
      });
    },
  },
};
</script>

<style></style>
<template>
    <div class="page-scan">
      <!--返回-->
      <van-nav-bar title="扫描二维码/条形码" fixed
        @click-left="clickIndexLeft()"
        class="scan-index-bar">
        <template #left>
          <van-icon name="arrow-left" size="18" color="#fff"/>
          <span style="color: #fff"> 取消 </span>
        </template>
      </van-nav-bar>
      <!-- 扫码区域 -->
      <video ref="video" id="video" class="scan-video" autoplay></video>
      <!-- 提示语 -->
      <div v-show="tipShow" class="scan-tip"> {{tipMsg}} </div>
    </div>
  </template>
   
  <script>
  import { BrowserMultiFormatReader } from '@zxing/library';
  import { Dialog, Notify } from 'vant';
   
    export default {
      name: 'scanCodePage',
      data() {
        return {
          loadingShow: false,
          codeReader: null,
          scanText: '',
          vin: null,
          tipMsg: '正在尝试识别....',
          tipShow: false
        }
      },
      created() {
        this.codeReader = new BrowserMultiFormatReader();
        this.openScan();
      },
      destroyed(){
        this.codeReader.reset();
      },
      watch: {
        '$route'(to, from) {
          if(to.path == '/scanCodePage'){
            this.codeReader = new BrowserMultiFormatReader();
            this.openScanTwo();
          }
        }
      },
      methods: {
        async openScan() {
          this.codeReader.getVideoInputDevices().then((videoInputDevices) => {
            this.tipShow = true;
            this.tipMsg = '正在调用摄像头...';
            console.log('videoInputDevices', videoInputDevices);
            // 默认获取第一个摄像头设备id
            let firstDeviceId = videoInputDevices[0].deviceId;
            // 获取第一个摄像头设备的名称
            const videoInputDeviceslablestr = JSON.stringify(videoInputDevices[0].label);
            if (videoInputDevices.length > 1) {
              // 判断是否后置摄像头
              if (videoInputDeviceslablestr.indexOf('back') > -1) {
                firstDeviceId = videoInputDevices[0].deviceId;
              } else {
                firstDeviceId = videoInputDevices[1].deviceId;
              }
            }
            this.decodeFromInputVideoFunc(firstDeviceId);
          }).catch(err => {
            this.tipShow = false;
            console.error(err);
          });
        },
        async openScanTwo() {
          this.codeReader = await new BrowserMultiFormatReader();
          this.codeReader.getVideoInputDevices().then((videoInputDevices) => {
            this.tipShow = true;
            this.tipMsg = '正在调用摄像头...';
            console.log('videoInputDevices', videoInputDevices);
            // 默认获取第一个摄像头设备id
            let firstDeviceId = videoInputDevices[0].deviceId;
            // 获取第一个摄像头设备的名称
            const videoInputDeviceslablestr = JSON.stringify(videoInputDevices[0].label);
            if (videoInputDevices.length > 1) {
              // 判断是否后置摄像头
              if (videoInputDeviceslablestr.indexOf('back') > -1) {
                firstDeviceId = videoInputDevices[0].deviceId;
              } else {
                firstDeviceId = videoInputDevices[1].deviceId;
              }
            }
            this.decodeFromInputVideoFunc(firstDeviceId);
          }).catch(err => {
            this.tipShow = false;
            console.error(err);
          });
        },
        decodeFromInputVideoFunc(firstDeviceId) {
          this.codeReader.reset(); // 重置
          this.scanText = '';
          this.codeReader.decodeFromInputVideoDeviceContinuously(firstDeviceId, 'video', (result, err) => {
            this.tipMsg = '正在尝试识别...';
            this.scanText = '';
            if (result) {
              console.log('扫描结果', result);
              this.scanText = result.text;
              if (this.scanText) {
                this.tipShow = false;
                // 这部分接下去的代码根据需要,读者自行编写了
                // this.$store.commit('app/SET_SCANTEXT', result.text);
                // console.log('已扫描的小票列表', this.$store.getters.scanTextArr);
              }
            }
            if (err && !(err)) {
              this.tipMsg = '识别失败';
              setTimeout(() => {
                this.tipShow = false;
              }, 2000)
              console.error(err);
            }
          });
        },
        clickIndexLeft(){  // 返回上一页
          this.codeReader = null;
          this.$destroy();
          this.$router.back();
        }
      }
    }
  </script>
   
  <style lang="scss">
  .scan-index-bar{
    background-image: linear-gradient( -45deg, #42a5ff ,#59cfff);
  }
  .van-nav-bar__title{
    color: #fff !important;
  }
  .scan-video{
    height: 80vh;
  }
  .scan-tip{
    width: 100vw;
    text-align: center;
    margin-bottom: 10vh;
    color: white;
    font-size: 5vw;
  }
  .page-scan{
    overflow-y: hidden;
    background-color: #363636;
  }
  </style>

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
公众号vue页面调用手机摄像头扫码功能,需要使用vue的相关组件和插件。首先,需要使用vue-router进行路由控制,将扫码页面添加到路由中。在扫码页面中,需要使用Vue Quagga组件,该组件是基于QuaggaJS开发的二维码扫描器,能够轻松地在移动设备上运行。同时,还需要使用vue-web-cam组件实现调用手机摄像头的功能。该组件支持通过getUserMedia API调用前置或后置相机,并可以实时预览相机画面。具体实现过程如下: 1. 安装Vue Quagga和vue-web-cam插件 通过npm安装Vue Quagga和vue-web-cam插件: ``` npm install vue-quagga vue-web-cam ``` 2. 在扫码页面中引入组件 在扫码页面的Vue组件中,引入Vue Quagga组件以及vue-web-cam组件: ``` import VueQuagga from 'vue-quagga' import VueWebCam from 'vue-web-cam' export default { components: { VueQuagga, VueWebCam } // ... } ``` 3. 在扫码页面中添加Quagga配置项 在扫码页面的Vue组件中,添加Quagga的配置项,并设置回调函数处理扫码结果。例如: ``` <template> <div> <vue-web-cam ref="webcam" width="100%" :videoConstraints="{facingMode:'environment'}"></vue-web-cam> <vue-quagga v-if="showCamera" :config="quaggaConfig" @detect="detectHandler"></vue-quagga> </div> </template> <script> export default { data () { return { quaggaConfig: { inputStream: { name: "Live", type: "LiveStream", constraints: { width: {min: 640}, height: {min: 480}, facingMode: "environment" } }, decoder: { readers: ['ean_reader', 'upc_reader'] }, locate: true }, showCamera: true } }, methods: { detectHandler (result) { console.log(result.codeResult.code) } } } </script> ``` 4. 在扫码按钮点击事件中开始调用摄像头扫码按钮的点击事件中,使用Vue Web Cam组件的start()方法开始调用前置摄像头: ``` <template> <div> <button @click="startScan">开始扫码</button> <vue-web-cam ref="webcam" width="100%" :videoConstraints="{facingMode:'environment'}"></vue-web-cam> <vue-quagga v-if="showCamera" :config="quaggaConfig" @detect="detectHandler"></vue-quagga> </div> </template> <script> export default { data () { return { quaggaConfig: { // ... }, showCamera: false } }, methods: { startScan () { this.showCamera = true this.$refs.webcam.start() }, detectHandler (result) { console.log(result.codeResult.code) } } } </script> ``` 至此,公众号vue页面调用手机摄像头扫码功能已经实现。用户在点击页面上的扫码按钮后,会弹出调用前置摄像头的提示框,扫码识别成功后会将结果输出到控制台上。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值