H5或者Vue实现二维码识别
前言
1、扫码识别库采用开源的@zxing/library
2、支持js,Vue,lit等实现
原文章地址和代码仓库地址
1、在界面创建video标签用来显示摄像头内容
<!-- 视区 --><!-- lit写法 -->
<video ${ref(this.videoRef)} class="xy-scan-wrap-video" autoplay></video><!-- vue2 -->
<video ref="videoRef" class="xy-scan-wrap-video" autoplay></video><!-- vue3 -->
<video ref={videoRef} class="xy-scan-wrap-video" autoplay></video><!-- js -->
<video id="video" class="xy-scan-wrap-video" autoplay></video>
2、创建扫码对象BrowserMultiFormatReader
import { BrowserMultiFormatReader } from '@zxing/library';/*** 实例*/
private codeReader = new BrowserMultiFormatReader();
3、获取设备的摄像头列表
this.codeReader.listVideoInputDevices().then((videoInputDevices) = >{console.log('[xy-scan] videoInputDevices', videoInputDevices);if (videoInputDevices.length > 0) {// 记录一下扫描到的摄像头数量,这个videoInputDevices是个数组,里面有扫描到的摄像头数据this.listVideoInputDevices = videoInputDevices;return videoInputDevices;}return [];
}).
catch((e) = >{console.error('[xy-scan] listVideoInputDevices', e);return [];
})
4、选择摄像头,开始打开摄像头扫码
this.codeReader.reset(); // 重置
this.resultContent = ''; // 重置
// 设备id
// 切换摄像头,有时候我们取的摄像头不对,就需要切换摄像头,currentDeviceIndex代表摄像头索引
const deviceId = this.listVideoInputDevices[this.currentDeviceIndex] ? .deviceId;// 调用库
// this.videoRef.value表示步骤1创建的video节点,原生js可以使用document获取,Vue可以通过refs获取
this.codeReader.decodeFromVideoDevice(deviceId, this.videoRef.value, (result) = >{this.resultContent = '';// 扫描成功 这个result就是扫描结果,长啥样自己打印出来看看if (result) {// 扫描获取的文字,此时可以进行业务相关逻辑this.resultContent = result.getText();}
});