掘金刷到的一篇文章,来自https://juejin.cn/post/7316795553798815783,收藏记录
适用于vue2 适用于多款主流浏览器
npm install html5-qrcode
引入 import { Html5Qrcode } from 'html5-qrcode';
代码使用
<view class="reader-box" v-if="isScaning">
<view class="reader" id="reader"></view>
</view>
<script>
export default {
data(){
return{
html5Qrcode: null,
isScaning: false,
}
},
methods:{
openQrcode() {
this.isScaning = true;
Html5Qrcode.getCameras().then((devices) => {
if (devices && devices.length) {
this.html5Qrcode = new Html5Qrcode('reader');
this.html5Qrcode.start(
{ facingMode: 'environment'},
{
focusMode: 'continuous', //设置连续聚焦模式
fps: 5, //设置扫码识别速度
qrbox: 280 //设置二维码扫描框大小
},
(decodeText, decodeResult) => {
if (decodeText) { //这里decodeText就是通过扫描二维码得到的内容
this.action(decodeText) //对二维码逻辑处理
this.stopScan(); //关闭扫码功能
}
},
(err) => {
// console.log(err); //错误信息
}
);
}
});
},
stopScan() {
console.log('停止扫码')
this.isScaning = false;
if(this.html5Qrcode){
this.html5Qrcode.stop();
}
}
}
}
</script>
<style>
.reader-box {
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
background-color: rgba(0, 0, 0, 0.5);
}
.reader {
width:100%;
// width: 540rpx;
// height: 540rpx;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
作者:极客转
链接:https://juejin.cn/post/7316795553798815783