吐槽:某厂的开发文档写的跟屎一样
1、后台返回accessToken,小程序请求获取小程序码
uni.request({
url: 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' + res.data.accessToken,
method: 'POST',
headers: {
'Content-Type': 'json'
},
responseType: 'arraybuffer',
data: {
"scene": "a=1", // 参数
"is_hyaline": true //透明底色
},
success: (res) => {
// 将返回的图片buffer生成图片,并保存至临时用户文件中
const fs = wx.getFileSystemManager();
const FILE_BASE_NAME = 'code';
let filePath = `${wx.env.USER_DATA_PATH}/${FILE_BASE_NAME}.png`;
fs.writeFileSync(filePath, res.data)
// filePath就是图片的本地路径
that.filePath = filePath
that.qrcode(filePath)
},
fail(e) {
console.log(e)
}
});
2、将生成的小程序码绘制到海报上 --- canvas
let that = this
const query = wx.createSelectorQuery()
query.select('#myCanvas')
.fields({
node: true,
size: true
})
.exec((res) => {
const canvas = res[0].node
const ctx = canvas.getContext('2d')
const headerImg = canvas.createImage();
const backImg = canvas.createImage();
headerImg.src = that.filePath;
backImg.src = '../../static/wish.png';
backImg.onload = () => {
ctx.drawImage(backImg, 0, 0, 150, 100)
}
headerImg.onload = () => {
ctx.drawImage(headerImg, 0, 0, 150, 100)
}
})
3、将生成的小程序码绘制到海报上 --- canvas离屏绘制
// 创建离屏 2D canvas 实例
const canvas = wx.createOffscreenCanvas({
type: '2d',
width: 300,
height: 150
})
// 获取 context。注意这里必须要与创建时的 type 一致
const context = canvas.getContext('2d')
// 创建一个图片
const image = canvas.createImage()
// 等待图片加载
image.src = '../../static/wish.png' // 要加载的图片 url
image.onload = () => {
// 把图片画到离屏 canvas 上
context.clearRect(0, 0, 300, 150)
context.drawImage(image, 0, 0, 300, 150)
// 获取画完后的数据
const imgData = context.getImageData(0, 0, 300, 150)
console.log(imgData)
// 图片的base64格式
console.log(context.canvas.toDataURL())
that.src = context.canvas.toDataURL()
}