vue3+zxing 实现h5浏览器扫描二维码

9,351 阅读1分钟

xdm第一次写文章,不足之处请指出修改。

安装zxing库

npm install @zxing/library --save

vue中引入

import { BrowserMultiFormatReader } from "@zxing/library"

提示

此代码需要在 https环境下 才能调用摄像头

代码实现 js代码

export default defineComponent({
  setup(props) {
    let codeReader = reactive(new BrowserMultiFormatReader());
    onMounted(() => {
      openScan();
    });
    let openScan = async () => {
      codeReader
        .listVideoInputDevices()
        .then((videoInputDevices) => {
          console.log("videoInputDevices", videoInputDevices, "摄像头设备");

          // 默认获取第一个摄像头设备id
          let firstDeviceId = videoInputDevices[0].deviceId;  // 根据id选择摄像头

          decodeFromInputVideoFunc(firstDeviceId);
          // navigator.getUserMedia(
          //   { video: { deviceId: firstDeviceId } },
          //   () => {
          //     console.log(document.cookie);
          // decodeFromInputVideoFunc(firstDeviceId);
          //   },
          //   () => {
          //     Toast("请关闭链接,重新进入");
          //     router.back();
          //   }
          // );
        })
        .catch((err) => {});
    };

    let decodeFromInputVideoFunc = (firstDeviceId: any) => {
      codeReader.decodeFromInputVideoDeviceContinuously(
        null,    // firstDeviceId  为null 时默认选择面向环境的摄像头
        "video",
        (result: any, err) => {
          if (result) {
            console.log(result, "扫描结果");
          }
          if (err && !err) {
            console.error(err);
          }
        }
      );
    };

    onBeforeUnmount(() => {
      codeReader.reset();
    });
    return {};
  },
});
listVideoInputDevices  //获取摄像头设备得到一个摄像头设备数组,根据摄像头的id选择使用的摄像头

decodeFromInputVideoDeviceContinuously() //第一个参数为前面数组得到的摄像头的id,根据传入的摄像头id 选择摄像头扫描 ,id为null时 默认使用面向环境的摄像头

html 代码

<div class="QrCode">
    <video ref="video" height="100%" width="100%" id="video" autoplay></video>
  </div>
  <div class="Qr_scanner">
    <div class="box">
      <div class="line_row">
        <div class="line"></div>
      </div>
      <div class="angle"></div>
    </div>
  </div>

源码地址

github源码地址

zxing库github地址

css动画百度找的一个老哥的动画