1. 背景
uniapp 中自带的 uni.scanCode 只能应用于 非H5,在H5上是没有提供该类扫码功能。 在参考了前辈的文章后(在此特别感谢 uniapp H5扫码实现 提供的方案和灵感),本文的解决方案是:通过调用相机拍照,拍完进行二维码识别。
2. 效果
完整demo下载地址(希望花您两秒钟的时间点个 star,这将是我持续创作的动力):https://gitee.com/Jokerlsss/h5-scan-code ![在这里插入图片描述](https://img-blog.csdnimg.cn/8383fcd1120d4bbcb839d168ce2018c7.png)
点击按钮调起相机(或相册)拍照(或选择照片)后确认,自动识别二维码可识别带 中文 的数据
3. 代码
扫码
扫码结果:{{qrCodeRes}}
let Qrcode = require('../../utils/reqrcode.js')
export default {
data() {
return {
qrCodeRes: ''
}
},
methods: {
// 扫码
scanCode() {
// #ifdef APP-PLUS
this.scanCodeAPP()
// #endif
// #ifdef H5
this.scanCodeH5()
// #endif
},
// APP直接调用 uni.scanCode 接口
scanCodeAPP() {
uni.scanCode({
scanType: ['qrCode'],
success: (res) => {
this.qrCodeRes = res.result
}
})
},
// H5通过拉起相机拍照来识别二维码
scanCodeH5() {
uni.chooseImage({
count: 1,
success: imgRes => {
Qrcode.qrcode.decode(this.getObjectURL(imgRes.tempFiles[0]))
Qrcode.qrcode.callback = (codeRes) => {
if (codeRes.indexOf('error') >= 0) {
// 二维码识别失败
this.qrCodeRes = '不合法二维码:' + codeRes
} else {
// 二维码识别成功
let r = this.decodeStr(codeRes)
this.qrCodeRes = r
}
}
}
})
},
// 获取文件地址函数
getObjectURL(file) {
var url = null
if (window.createObjectURL !== undefined) { // basic
url = window.createObjectURL(file)
} else if (window.URL !== undefined) { // mozilla(firefox)
url = window.URL.createObjectURL(file)
} else if (window.webkitURL !== undefined) { // webkit or chrome
url = window.webkitURL.createObjectURL(file)
}
return url
},
// 解码,输出:中文
decodeStr(str) {
var out, i, len, c;
var char2, char3;
out = "";
len = str.length;
i = 0;
while (i > 4) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
// 0xxxxxxx
out += str.charAt(i - 1);
break;
case 12:
case 13:
// 110x xxxx 10xx xxxx
char2 = str.charCodeAt(i++);
out += String.fromCharCode(((c & 0x1F) |