最近在开发微信小程序时,遇到一个需要将服务端接口返回的base64格式的字符串转为二维码展示,在参考了一些大佬的思路后,最终顺利完成此功能。以下是我的思路及示例代码。
- 项目结构
我习惯在项目的工具类目录下创建单独的文件夹以区分其他的工具,不这样分也可以,只是后面import的时候相对路径需要根据自己实际的修改。 - 工具类
encryption.js,JSEncrypt.js,qrcode.js我已上传网盘,在文末有链接和提取码,自行获取。 - 生成二维码
最重要的部分是qrcodeAction.js,这是生成二维码的关键,所需的二维码参数都在这里转换或定义。代码如下:
import { base64DecToArr, uint8ArrayToString } from './encryption';
function getQrcodeParams(config) {
if (config && config.qrcode) {
let qrArr = base64DecToArr(config.qrcode);
let strInUtf = uint8ArrayToString(qrArr);
const baseWidth = config.width;
const baseHeight = config.height;
const canvasId = config.id;
const newAllWidth = wx.getSystemInfoSync().windowWidth;
const codeWidth = (newAllWidth * baseWidth) / 750;
const codeHeight = (newAllWidth * baseHeight) / 750;
return {
text: strInUtf,
width: codeWidth,
height: codeHeight,
correctLevel: config.correctLevel || 0,
image: {
imageResource: '/image/logo.png',
width: 80, // 建议不要设置过大,以免影响扫码
height: 80, // 建议不要设置过大,以免影响扫码
round: false // Logo图片是否为圆形
},
canvasId: canvasId
};
} else {
return null;
}
}
module.exports = {
getQrcodeParams: getQrcodeParams
}
- 实际使用
以下是我在实际页面使用的例子,供参考。
a.在data定义codeInfo对象
codeInfo: {
width: 470,
height: 470,
qrcode: '',
correntLevel: 0,
foreground: '#000000'
}
b.引入QrcodeAction和QRcode方法
import QrcodeAction from '../../utils/qr_code/qrcodeAction.js';
import { QRcode } from '../../utils/qr_code/qrcode.js'
c.在页面引入画布组件
<canvas style="width: {{codeInfo.width}}rpx; height: {{codeInfo.height}}rpx;" canvas-id="codewrap"></canvas>
d.生成二维码
let codeInfo = that.data.codeInfo
codeInfo.qrcode = data.data.codeContent
codeInfo = Object.assign(codeInfo, {id: 'codewrap'})
let params = QrcodeAction.getQrcodeParams(codeInfo)
if (params && params.text) {
QRcode(params)
}
以上是我在我自己项目中使用的过程,供参考,实际使用还需要大家灵活变通。
附:encryption.js,JSEncrypt.js,qrcode.js资源
链接:https://pan.baidu.com/s/1r8HPxgMoo_ZpHA6284Ckmw
提取码:e3zs