使用html5-qrcode实现 github:https://github.com/mebjas/html5-qrcode
电脑手机都可以
<div id="reader"></div>
let html5QrCode = new Html5Qrcode("reader");
let reader = document.getElementById("reader");
let config = { fps: 10, qrbox: { width: 300, height: 280 } }; //扫一扫相关设置
//相机授权
function useCamera() {
reader.style.display = "block";
Html5Qrcode.getCameras()
.then((devices) => {
console.log(devices, '判断')
if (devices && devices.length) {
let cameraId = "";
if (devices.length == 1) {
cameraId = devices[0].id; //前置摄像头
} else {
cameraId = devices[1].id; //后置摄像头
}
if (cameraId) {
startWithCameraId(cameraId);
}
}
})
.catch((err) => {
console.log("没有获取摄像头设备...");
});
}
//相机
function startWithCameraId(cameraId) {
html5QrCode
.start(
{ deviceId: { exact: cameraId } },
config,
onScanSuccess,
onScanFailure
)
.catch((err) => {
console.log("通过摄像头扫码异常....", err);
});
}
//扫码解析成功
function onScanSuccess(decodedText, decodedResult) {
//暂停扫码
html5QrCode.stop().then((ignore) => {
$("#device_no").val(decodedText)
verifyDevice()
html5QrCode.clear() //清除画布
// console.log("扫码成功结果:\n" + decodedText)
}).catch((err) => {
console.log(err)
});
}
//扫码解析失败
function onScanFailure(error) {
console.log("扫码失败:\n" + error)
}