Skip to content

H5 扫描二维码

在 H5 可以使用 html5-qrcode 库来调用设备摄像头,扫描二维码。

安装

bash
npm install html5-qrcode

DEMO 示例

vue
<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue';
import { Html5Qrcode } from 'html5-qrcode';

const isShow = ref(false);
let html5QrCode: Html5Qrcode | null = null; // 更精确的类型定义

// 初始化时执行
onMounted(() => {
  initializeScanner();
});

// 卸载组件时停止扫描
onUnmounted(() => {
  stopScanner();
});

// 初始化并获取摄像头设备
const initializeScanner = async () => {
  try {
    const devices = await Html5Qrcode.getCameras();
    if (devices && devices.length > 0) {
      isShow.value = true;
      html5QrCode = new Html5Qrcode('reader');
      startScanner();
    } else {
      alert('没有找到摄像头设备');
    }
  } catch (error) {
    console.error('获取设备信息失败', error);
    alert('无法获取摄像头设备信息,请检查设备权限。');
  }
};

// 开始二维码扫描
const startScanner = () => {
  if (!html5QrCode) return;

  const { innerWidth: width, innerHeight: height } = window;

  html5QrCode
    .start(
      { facingMode: 'environment' },
      {
        fps: 20,
        qrbox: { width: 300, height: 300 },
        aspectRatio: width / height,
      },
      (decodedText) => {
        alert(`扫码结果: ${decodedText}`);
      },
      (errorMessage) => {
        console.debug('扫描中无结果', errorMessage);
      },
    )
    .catch((error) => {
      console.error('启动扫描失败', error);
    });
};

// 停止二维码扫描
const stopScanner = async () => {
  if (!html5QrCode) return;

  try {
    await html5QrCode.stop();
    console.log('二维码扫描已停止');
  } catch (error) {
    console.error('停止扫描失败', error);
  }
};
</script>

<template>
  <div v-if="isShow" class="container">
    <div id="reader"></div>
  </div>
</template>

<style scoped lang="scss">
.container {
  position: fixed;
  top: 0;
  left: 0;
  height: 100vh;
  width: 100%;
  background: rgba(0, 0, 0, 0.48);
  z-index: 999;
  display: flex;
  justify-content: center;
  align-items: center;
}

#reader {
  width: 300px;
  height: 300px;
}
</style>