核心原理: 生成Base64形式的二维码,qrcode-base64
安装 :npm i [email protected]
代码实现
1、引入该库
const QR = require("qrcode-base64");
2、封装绘制二维码函数
drawQRcode() {
//绘制二维码
var that = this
const imgData = QR.drawImg('http://xxx.xxx.xxx/二维码链接', {
typeNumber: 4,
errorCorrectLevel: 'M',
size: 500,
canvasId: 'oss-canvas'
})
const fs = wx.getFileSystemManager()
const times = new Date().getTime()
const codeimg = wx.env.USER_DATA_PATH + '/' + times + '.png' //保证图片路径的唯一性
fs.writeFile({
filePath: codeimg,
data: imgData.slice(22),
encoding: 'base64',
success: (res) => {
that.setData({
qrImage: codeimg //二维码图片
})
}
});
},
为什么用
FileSystemManager.writeFile
?因为base64 格式图片数据,无法被 getImageInfo直接调用,首先将 base64 数据 —> ArrayBuffer 数据,然后通过使用
FileSystemManager.writeFile
将 ArrayBuffer 数据—>本地用户路径的二进制图片文件,此时该二进制图片文件存储在wx.env.USER_DATA_PATH 中,Canvas可以直接根据该路径绘制出二维码图片。
3、Canvas 绘制二维码图片
getCanvas(){
var that = this
wx.showLoading({
title: '图片处理中',
mask: true,
icon: 'loading',
duration: 1000
})
that.canvas = wx.createCanvasContext("image-canvas", that)
that.canvas.drawImage(that.data.qrImage, that.data.width , that.data.height , 38, 38)
setTimeout(function () {
//导出图片
wx.canvasToTempFilePath({
canvasId: "image-canvas",
x: that.data.width,
y: that.data.height,
width: that.data.width,
height: that.data.height,
destWidth: that.data.width * that.data.pixelRatio,
destHeight: that.data.height * that.data.pixelRatio,
fileType: 'png',
quality: 1,
success: function (res) {
that.setData({
localImage: res.tempFilePath,
})
wx.hideLoading()
}
})
}, 250)
}