在 UniApp 的 H5 环境中,由于无法直接调用原生摄像头 API,实现扫码功能通常需要借助第三方 JavaScript 库(如 html5-qrcode)或结合后端服务。以下是使用 html5-qrcode 库的推荐方案:
实现步骤
-
安装依赖
在项目中引入 html5-qrcode 库:
npm install html5-qrcode
-
页面代码示例
<template>
<view>
<button @click="startScan">开始扫码</button>
<button @click="stopScan">停止扫码</button>
<div id="qr-reader" style="width: 300px"></div>
<p>扫码结果: {{ result }}</p>
</view>
</template>
<script>
import { Html5Qrcode } from 'html5-qrcode';
export default {
data() {
return {
scanner: null,
result: ''
};
},
methods: {
async startScan() {
this.scanner = new Html5Qrcode("qr-reader");
try {
await this.scanner.start(
{ facingMode: "environment" }, // 使用后置摄像头
{ fps: 10, qrbox: 250 },
(decodedText) => {
this.result = decodedText;
this.stopScan(); // 获取结果后停止扫描
},
(errorMessage) => {
console.warn("扫码失败:", errorMessage);
}
);
} catch (err) {
console.error("摄像头启动失败:", err);
}
},
stopScan() {
if (this.scanner) {
this.scanner.stop().then(() => {
this.scanner.clear();
}).catch(err => console.error("停止失败:", err));
}
}
},
onUnload() {
this.stopScan(); // 页面卸载时停止扫描
}
};
</script>
注意事项
-
兼容性
- 需在 HTTPS 环境或本地调试(localhost)下运行。
- 部分移动端浏览器可能不支持直接访问摄像头。
-
用户体验
- 首次使用需授权摄像头权限。
- 可自定义扫描框样式(通过
qrbox 参数调整)。
-
备选方案
扩展建议
- 对扫码结果进行有效性校验(如URL格式、特定前缀)。
- 在
onUnload 生命周期中清理资源,避免内存泄漏。
以上方案在主流浏览器(Chrome、Safari)中测试通过,实际部署时建议进行真机调试。