第一次写识别条形码二维码,一开始没有头绪 成功后很简单
实现最基本扫码功能的demo,样式你们可以自己加
/* 首先安装npm i @zxing/library (笔者这里使用的是"@zxing/library": "^0.19.1"版本)
* 主要是以下两个方法
* 1、listVideoInputDevices
* 获取摄像头设备得到一个摄像头设备数组,根据摄像头的id选择使用的摄像头
* 2、decodeFromInputVideoDeviceContinuously()
* 第一个参数为前面数组得到的摄像头的id,根据传入的摄像头id 选择摄像头扫描 ,id为null时 默认使用面向环境的摄像头
*/
import React, { useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { BrowserMultiFormatReader } from '@zxing/library'
export default function ScanCode() {
const navigate = useNavigate()
const codeReader = new BrowserMultiFormatReader()
useEffect(() => {
openScan()
}, [])
async function openScan() {
codeReader.listVideoInputDevices().then((videoInputDevices) => {
// console.log('videoInputDevices', videoInputDevices)
// 默认获取第一个摄像头设备id
let firstDeviceId = videoInputDevices[0].deviceId
decodeFromInputVideoFunc(firstDeviceId);
}).catch(err => {
// console.error(err);
})
}
function decodeFromInputVideoFunc(firstDeviceId) {
// firstDeviceId 为null 时默认选择面向环境的摄像头
codeReader.decodeFromInputVideoDeviceContinuously(firstDeviceId, 'video', (result, err) => {
if (result) { //扫码成功后 (你们可以做自己的操作)
// navigate('/login', { state: { code: result } })
window.location.reload() // 强制页面刷新 关闭摄像头
}
if (err) {
// console.error(err);
}
})
}
return <video id="video" />
}
最新版 decodeFromInputVideoDeviceContinuously() 已不推荐使用-改用decodeFromVideoDevice
// codeReader.decodeFromInputVideoDeviceContinuously(firstDeviceId, 'video', (result, err) => {
// if (result) { //扫码成功后 (你们可以做自己的操作)
// navigate('/login', { state: { code: result } })
// window.location.reload() // 强制页面刷新 关闭摄像头
// }
// if (err) {
// // console.error(err);
// }
// })
codeReader.decodeFromVideoDevice(firstDeviceId, 'video', (result, err) => {
if (result) { //扫码成功后 (你们可以做自己的操作)
navigate('/login', { state: { code: result } })
window.location.reload() // 强制页面刷新 关闭摄像头
}
if (err) {
// console.error(err);
}
})