摘要:
扫描二维码是app常用的一种基础功能,该功能使用户能够方便地登录、浏览网站、获取信息等操作,鉴于此,把该功能引入H5,利用H5实现扫描二维码功能
在把扫描二维码功能引入H5的过程中,通过对比5种工具库找到了两种比较好用的第三方库。接下来就对这两种库进行记录。
本文使用的技术是uniapp+vue3
html5-qrcode库是一个JavaScript库,只需要提供一个元素容器即可实现扫码功能,但是扫描的效率很低,对着二维码1个小时都不一定能识别出来。
使用这个库也很简单:
npm install html5-qrcode
<template>
<view class="container">
<button class="scan" @click="scanCode">扫一扫button>
<view class="reader-box" v-if="isScaning">
<view class="reader" id="reader">view>
view>
view>
template>
<script>
import {
Html5Qrcode
} from 'html5-qrcode';
export default {
data() {
return {
html5Qrcode: null,
isScaning: false,
}
},
methods: {
startScan() {
this.isScaning = true;
Html5Qrcode.getCameras().then(devices => {
if (devices && devices.length) {
this.html5Qrcode = new Html5Qrcode('reader');
this.html5Qrcode.start({
facingMode: 'environment',
}, {
fps: 24,
qrbox: 280
}, (decodeText, decodeResult) => {
console.log(decodeText)
if (decodeText) {
this.stopScan();
this.isScaning = false;
}
}, (err) => {
console.log(err)
});
}
});
},
stopScan() {
this.html5Qrcode.stop();
},
scanCode() {
console.log('helo')
this.startScan();
}
}
}
</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>
上面的样式可以根据自己的需要进行修改。
html5-qrcode的优点:
vue-qrcode-reader的使用更简单
npm install vue-qrcode-reader
下面使用一个示例,看看效果:
<template>
<view class="container">
<button class="scan" @click="scanCode">扫一扫</button>
<view class="reader-box" v-if="isScaning">
<QrcodeStream @detect="onDetect">
<view class="reader"></view>
</QrcodeStream>
</view>
</view>
</template>
<script>
import {
QrcodeStream,
} from 'vue-qrcode-reader';
export default {
components: {
QrcodeStream,
},
data() {
return {
isScaning: false,
}
},
methods: {
onDetect(detectedCodes) {
const target = detectedCodes[0];
if (target && target.rawValue) {
console.log(target.rawValue);
this.isScaning = false;
}
},
scanCode() {
this.isScaning = true;
}
}
}
</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 {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
height: 100%;
}
</style>
当点击扫一扫时出现下面的效果:
上面的样式可以根据自己的需要进行修改,QrcodeStream提供了一个默认的插槽,插槽的内容默认在一个position:absolute
的盒子里。
vue-qrcode-reader的优点
vue-qrcode-reader的缺点: