2022年5月24日
uni-app使用html5-qrcode支持H5调用摄像头扫码
首先uni-app项目执行安装npm i html5-qrcode,demo如下:
<template>
<div id="reader" width="400rpx"></div>
</template>
<script>
import {Html5Qrcode} from "html5-qrcode";
export default {
data() {
return {
cameraId: '',
html5QrCode: ''
}
},
onLoad() {
this.getCameras()
},
methods: {
stop() {
this.html5QrCode
.stop()
.then(ignore => {
// QR Code scanning is stopped.
console.log('QR Code scanning stopped.');
})
.catch(err => {
// Stop failed, handle it.
console.log('Unable to stop scanning.');
});
},
start() {
this.html5QrCode = new Html5Qrcode("reader");
this.html5QrCode
.start(
this.cameraId, // retreived in the previous step.
{
fps: 10, // sets the framerate to 10 frame per second
qrbox: 250 // sets only 250 X 250 region of viewfinder to
// scannable, rest shaded.
},
qrCodeMessage => {
// do something when code is read. For example:
if (qrCodeMessage) {
console.log(qrCodeMessage)
}
},
errorMessage => {
// parse error, ideally ignore it. For example:
// console.log(`QR Code no longer in front of camera.`);
}
)
.catch(err => {
// Start failed, handle it. For example,
console.log(`Unable to start scanning, error: ${err}`);
this.$refs.uToast.show({
title: `扫码失败:${err}`,
type: 'error'
});
});
},
getCameras() {
Html5Qrcode.getCameras()
.then((devices) => {
/**
* devices would be an array of objects of type:
* { id: "id", label: "label" }
*/
if (devices && devices.length) {
// 如果有2个摄像头,1为前置的
if (devices.length > 1) {
this.cameraId = devices[1].id;
} else {
this.cameraId = devices[0].id;
}
this.devices = devices;
this.start();
// .. use this to start scanning.
}
})
.catch((err) => {
// handle err
console.log(err); // 获取设备信息失败
});
},
}
}
</script>