最近有个需求就是需要做个h5的页面打开摄像头实现扫一扫功能
我这里用的是 html5-qrcode 官方文档也给出来案例可以自行搜索
> ** 必需写不然无法显示**
<div id="code">
<div id="qr-reader" style="width: 100%"></div>
</div>
import { Html5Qrcode } from 'html5-qrcode'
getCameras() {
Html5Qrcode.getCameras()
.then((devices) => {
if (devices && devices.length) {
// 如果有2个摄像头,1为前置的
if (devices.length > 1) {
this.cameraId = devices[1].id
} else {
this.cameraId = devices[0].id
}
this.devices = devices
// 显示扫码的dom
document.getElementById('code').style.display = 'block'
this.start()
}
})
.catch((err) => {
console.log(err) // 获取设备信息失败
})
},
start() {
this.html5QrCode = new Html5Qrcode('qr-reader')
this.html5QrCode
.start(
this.cameraId, // retreived in the previous step.
{
fps: 10, // 扫码的帧数
qrbox: 250 // 扫码的框
},
(decodedText, decodedResult) => {
if (decodedText) {
/// decodedText, decodedResult 返回的数据
this.stop()
}
},
(errorMessage) => {
console.log(errorMessage)
})
.catch((err) => {
console.log(`Unable to start scanning, error: ${err}`)
})
},
stop() {
this.html5QrCode
.stop()
.then((ignore) => {
// 隐藏扫码的dom
document.getElementById('code').style.display = 'none'
console.log('QR Code scanning stopped.')
})
.catch(() => {
console.log('Unable to stop scanning.')
})
},