摘要:
扫描二维码是app常用的一种基础功能,该功能使用户能够方便地登录、浏览网站、获取信息等操作,鉴于此,把该功能引入H5,利用H5实现扫描二维码功能
在把扫描二维码功能引入H5的过程中,通过对比5种工具库找到了两种比较好用的第三方库。接下来就对这两种库进行记录。
本文使用的技术是uniapp+vue3
html5-qrcode
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的优点:
- 灵活,不管是样式还是逻辑都可以根据自己的需要灵活处理
- 内置基本的样式,减少自定义样式的内容
html5-qrcode的缺点: - 灵敏度低,扫码扫一两个小时都不一定能够扫出结果,效率很慢
vue-qrcode-reader
vue-qrcode-reader的使用更简单
- 安装
npm install vue-qrcode-reader
- 在需要的页面引入QrcodeStream组件并注册即可使用
- 监听QrcodeStream的detect事件,事件处理函数的参数是识别到的二维码的数组
下面使用一个示例,看看效果:
<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的缺点:
- 没有内置的样式,需要自己写样式