时隔两年,我小飞飞又要更新文章啦!
最近项目上有个需求:微信小程序生成图片并保存到手机。图片中的动态元素有,一个二维码,几个文字信息。
拆分这个需求并实现。
1.利用canves元素,把从后台拿来的图片和文字写入的canves.
<Canvas canvasId="canvasImage" width="300" height="900" ></Canvas>
const ctx = wx.createCanvasContext('canvasImage')
ctx.rect(0, 0, 300, 550) //建一个画布
ctx.setFillStyle('#fff') //设置画布背景色
ctx.fill() //填充颜色
//把图片(图片必须是临时路径图片地址)放入画布的具体坐标位置,并设置图片再画布中大小
ctx.drawImage(res[0].path, 0, 0, _this.windowWidth, _this.windowWidth)
ctx.drawImage(res[1].path, 50,420,60,60) //头像图片
ctx.drawImage(qrPath, _this.windowWidth-35-100,420,80,80) //二维码图片
ctx.setFillStyle('#ccc') //设置颜色
ctx.setFontSize(14) //设置字体大小
ctx.fillText("邀你开启销售之旅", 30,520) //把字体写入画布具体坐标
ctx.fillText("长按识别二维码", _this.windowWidth-35-105,520) //
ctx.draw() //这一步写入完毕,闭合。
ctx.setFillStyle('#000000') //设置颜色
ctx.setFontSize(14) //设置字体大小
ctx.fillText(nickName, 40,495) //写入文字
ctx.draw(true) //写入完毕并退出画布操作
注意:写入画布中的图片地址必须是临时路径,获取图片临时路径方法如下:
wx.getImageInfo() //利用微信小程序获取图片临时路径
具体使用方法参看微信小程序官网:https://developers.weixin.qq.com/miniprogram/dev/api/media/image/wx.getImageInfo.html
2.canves生成图片。
wx.canvasToTempFilePath //画布转成临时图片路径地址
wx.saveImageToPhotosAlbum //利用临时画布路径地址生成图片并且保存到本地
两个api使用参考微信小程序官网
需要注意的是:我们在利用 wx.saveImageToPhotosAlbum 生成图片并且保存到手机的时候,需要手机授权。该api有一个faill的回调,可以在该回调中做手机未授权的逻辑业务操作。
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
fail:function (err) {
if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny" || err.errMsg === "saveImageToPhotosAlbum:fail authorize no response") {
// 这边微信做过调整,必须要在按钮中触发,因此需要在弹框回调中进行调用
wx.showModal({
title: '提示',
content: '需要您授权保存相册',
showCancel: false,
success: modalSuccess => {
wx.openSetting({
success(settingdata) {
console.log("settingdata", settingdata)
if (settingdata.authSetting['scope.writePhotosAlbum']) {
wx.showModal({
title: '提示',
content: '获取权限成功,再次点击图片即可保存',
showCancel: false,
})
} else {
wx.showModal({
title: '提示',
content: '获取权限失败,将无法保存到相册哦~',
showCancel: false,
})
}
},
fail(failData) {
console.log("failData", failData)
},
complete(finishData) {
console.log("finishData", finishData)
}
})
}
})
}
},
complete(res) {
showToast('已保存到相册')
wx.hideLoading()
}
})
基本完工!下班。