直接上代码:npm i html5-qrcode
javascript
<van-button class="scanButton" @click="stop" type="success">结束扫码</van-button>
<van-search v-model="searchName" show-action label="" placeholder="请输入姓名" @search="onSearch">
<template #action>
<div @click="getCameras">
<van-icon name="scan" />
扫码报到
</div>
</template>
</van-search>
import { Html5Qrcode } from 'html5-qrcode';
const getCameras = () => {
scanCodeSta.value = true;
// showToast('正在初始化扫码,请稍后');
showToast({
message: '正在初始化扫码,请稍后',
position: 'bottom',
});
Html5Qrcode.getCameras().then((devices) => {
if (devices && devices.length) {
// 如果有2个摄像头,1为前置的
if (devices.length > 1) {
cameraId.value = devices[1].id;
} else {
cameraId.value = devices[0].id;
}
devicesInfo.value = devices;
// start开始扫描
start();
}
}).catch((err) => {
console.log('获取设备信息失败', err); // 获取设备信息失败
showToast('获取设备信息失败');
});
}
const start = () => {
html5QrCode.value = new Html5Qrcode('reader');
setTimeout(() => {
closeToast();
}, 700);
html5QrCode.value.start(cameraId.value, {
focusMode: 'continuous', //设置连续聚焦模式
// fps: 10, // 设置每秒多少帧
fps: 5, //设置扫码识别速度
// qrbox: { width: '100%', height: '100%' }, // 设置取景范围
qrbox: { width: 320, height: 320 }, // 设置取景范围
// aspectRatio: 1.777778, // 可选,视频馈送需要的纵横比,(4:3--1.333334, 16:9--1.777778, 1:1--1.0)传递错误的纵横比会导致视频不显示
}, (decodedText, decodedResult) => {
// showToast('扫描的结果===', decodedText, decodedResult);
result.value = decodedText;
if (decodedText) {
stop();
handleScanCheckin();
}
}, (errorMessage) => {
// showToast('暂无扫描结果');
console.log('暂无扫描结果', errorMessage);
}).catch((err) => {
console.log(`Unable to start scanning, error: ${err}`);
});
}
const stop = () => {
scanCodeSta.value = false;
if (!html5QrCode.value) {
return;
}
html5QrCode.value.stop().then((ignore) => {
console.log('QR Code scanning stopped.', ignore);
}).catch((err) => {
console.log('Unable to stop scanning.', err);
});
}
:deep(#qr-shaded-region) {
overflow: hidden;
}
:deep(#qr-shaded-region::after) {
position: absolute;
content: '';
width: 100%;
top: 0;
left: 0;
transform: translateY(-100%);
height: 50px;
background: linear-gradient(180deg, rgba(0, 255, 51, 0) 43%, #00ff33 211%);
border-bottom: 1px solid #00ff33;
animation: scan-animation 2s linear infinite;
}
@keyframes scan-animation {
0% {
top: 0;
}
100% {
top: 100%;
}
}