侧边栏壁纸
博主头像
昂洋编程 博主等级

鸟随鸾凤飞腾远,人伴贤良品自高

  • 累计撰写 71 篇文章
  • 累计创建 79 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

H5调用手机摄像头实现扫码功能(Vue)

Administrator
2023-12-22 / 0 评论 / 0 点赞 / 59 阅读 / 0 字 / 正在检测是否收录...
温馨提示:
本文最后更新于2024-06-07,若内容或图片失效,请留言反馈。 部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

安装两个组件

html5-qrcode

npm install html5-qrcode

vant

npm install vant

示例代码

<template>
  <div v-show="isShow" class="container">
    <span>Scan-扫码</span>
    <div id="reader" />
  </div>
</template>

<script>
import { Html5Qrcode } from 'html5-qrcode'
import { showToast } from 'vant'

export default {
  data() {
    return {
      html5QrCode: null,
      isShow: false,
      devicesInfo: null
    }
  },
  mounted() {
    this.getCameras()
  },
  beforeDestroy() {
    this.stop()
  },
  methods: {
    getCameras() {
      console.log('开始获取摄像头信息...')
      Html5Qrcode.getCameras()
        .then((devices) => {
          if (devices && devices.length) {
            console.log('获取摄像头信息成功:')
            console.log(devices)
            this.devicesInfo = devices
            this.isShow = true
            this.html5QrCode = new Html5Qrcode('reader')
            // start开始扫描
            this.start()
          }
        })
        .catch((err) => {
          // handle err
          console.log('获取设备信息失败', err) // 获取设备信息失败
          showToast('获取设备信息失败')
        })
    },
    start() {
      this.html5QrCode
        .start(
          {facingMode: "environment" },
          {
            fps: 20, // 设置每秒多少帧
            qrbox: { width: 250, height: 250 } // 设置取景范围
            // scannable, rest shaded.
          },
          (decodedText, decodedResult) => {
            alert('扫码结果' + decodedText)
          },
          (errorMessage) => {
            // parse error, ideally ignore it. For example:
            // console.log(`QR Code no longer in front of camera.`);
            console.log('暂无额扫描结果', errorMessage)
          }
        )
        .catch((err) => {
          // Start failed, handle it. For example,
          console.log(`Unable to start scanning, error: ${err}`)
        })
    },
    stop() {
      if (this.devicesInfo) {
        this.html5QrCode
          .stop()
          .then((ignore) => {
            // QR Code scanning is stopped.
            console.log('QR Code scanning stopped.', ignore)
          })
          .catch((err) => {
            // Stop failed, handle it.
            console.log('Unable to stop scanning.', err)
          })
      }
    }
  }
}
</script>

<style scoped lang="scss">
.container {
  position: relative;
  top: 0px;
  left: 0px;
  height: 100vh;
  width: 100%;
  background: rgba($color: #000000, $alpha: 0.48);
  z-index: 999;
}
#reader {
  top: 50%;
  left: 0;
  transform: translateY(-50%);
}
</style>

测试

配置好页面路径,如 /scan
另外调取手机摄像头需要再https协议下才可以,如果有阿里云等云服务器可以申请免费的https证书
手机打开链接可测试效果,如果是PC打开需要电脑带有摄像头

0

评论区