项目需求:需要在ipad浏览器上访问uniapp vue2前端网页,扫描二维码录入信息
1.下载安装html5-qrcode
npm install html5-qrcode
2.html5-qrcode引入和使用
<template>
<view class="container">
<button class="scan" @click="openQrcode">点击扫码</button>
<view class="reader-box" v-if="isScaning">
<view class="reader" id="reader"></view>
</view>
<view>扫码内容:{{scanVal}}</view>
</view>
</template>
<script>
import { Html5Qrcode } from "html5-qrcode";
export default {
data() {
return {
html5QrCode: null,
isScaning: false,
cameraId: null,
scanVal: ''
}
},
methods: {
openQrcode() {
this.isScaning = true;
Html5Qrcode.getCameras().then((devices) => {
if (devices && devices.length) {
if (devices.length > 1) {
this.cameraId = devices[1].id;
} else {
this.cameraId = devices[0].id;
}
this.html5QrCode = new Html5Qrcode('reader');
this.startInit();
}
});
},
startInit() {
const that = this;
this.html5QrCode.start(
this.cameraId, // retreived in the previous step.
// {
// facingMode: "environment" // environment后置摄像头 user前置摄像头
// },
{
fps: 10, // sets the framerate to 10 frame per second
qrbox: 250 // sets only 250 X 250 region of viewfinder to
},
qrCodeMessage => {
uni.showModal({
title: 'success1',
content: JSON.stringify(qrCodeMessage),
showCancel: false
});
// do something when code is read. For example:
if (qrCodeMessage) {
//成功扫出码qrCodeMessage为扫码内容
//扫码成功记得关掉摄像
that.action(qrCodeMessage) //对二维码逻辑处理
that.stopScan(); //关闭扫码功能
}
},
errorMessage => {
// parse error, ideally ignore it. For example:
console.log('errorMessage', errorMessage);
}
)
.catch((err) => {
// 扫码错误信息
let message = "";
if (typeof err == "string") {
message = "识别失败";
} else {
if (err.name == "NotAllowedError") {
message = "您需要授予相机访问权限!";
}
if (err.name == "NotFoundError") {
message = "这个设备上没有摄像头!";
}
if (err.name == "NotSupportedError") {
message =
"摄像头访问只支持在安全的上下文中,如https或localhost!";
}
if (err.name == "NotReadableError") {
message = "相机被占用!";
}
if (err.name == "OverconstrainedError") {
message = "安装摄像头不合适!";
}
if (err.name == "StreamApiNotSupportedError") {
message = "此浏览器不支持流API!";
}
}
});
},
action(val) {
this.scanVal = val;
},
stopScan() {
console.log('停止扫码')
this.isScaning = false;
if (this.html5QrCode) {
this.html5QrCode.stop()
.then((ignore) => {
console.log("停止扫码", ignore);
})
.catch((err) => {
console.log(err);
showToast("停止扫码失败");
});
}
},
}
}
</script>
<style scoped>
.container{
height:100%;
}
.reader-box {
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
background-color: rgba(0, 0, 0, 0.5);
}
.reader {
width: 540rpx;
height: 540rpx;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
3.html必须发布成https才能调动手机的摄像头,在vue.config.js中开启https
module.exports = {
devServer: {
https:true,
}
}
4.最终效果