首先来看一下整体的一个效果就是下图这样子的
一.整理一下思路
1.首先要生成一个canvas画布
2.由于onShareAppMessage 不能是异步的哦,promise什么的,就当没有过一样。。所以我们在onload或者是onshow中调用,我主要是在获取PDP详细信息的接口中的complete方法去调用生成画布的方法
3.在onShareAppMessage的return对象中把上述生成的路径直接赋值给imageUrl
4.需要注意的是开发者工具中的图片会裂掉,所以最好在手机中查看(这也是排查了很久结果用手机分享的时候发现图片其实是有的)
二.实现代码
HTML
<canvas canvas-id="myCanvas" hidden="true" style="width:500rpx;height:400rpx;" />//注意这边使用的是hidden
获取PDP详情接口的complete方法中调用生成canvas画布
//获得详情页面数据
getDetailInfo: function () {
//判断有没有groupSn,没有就用productCode
var productId = {
"productCode": this.data.productCode,
};
$.get({
url: "goods",
port: "goods",
data: productId,
success: (res) => {
//成功后的功能代码
},
complete:res=>{
this.getLogoImage()//下载分享页面中的图片
},
})
},
// 下载logo图
getLogoImage: function (e) {
let url = this.data.goodsPic[0]
let url1, url2;
return new Promise((resolve, reject) => {
this.promiseFun(url).then((res) => {
url1 = res
var productImage = 'https://mpuat.ibaiqiu.com/img/public/whiteBg.jpg';
return this.promiseFun(productImage, 2)
}).then((res) => {
url2 = res;
this.createshareImg(url1, url2).then(res=>{
resolve(res)
});
})
})
},
//画布生成
createshareImg(mainPic,backPic){
var that = this;
return new Promise((resolve, reject) => {
var ctx = wx.createCanvasContext('myCanvas', that);
ctx.clearRect(0, 0,500, 400);
ctx.fillRect(0, 0, 500, 400);
ctx.drawImage(backPic, 0, 0, 500, 400);
ctx.drawImage(mainPic,21, 0, 200, 199);
ctx.draw(false, (res) => {
setTimeout(() => {
wx.canvasToTempFilePath({
canvasId: 'myCanvas',
success: function (res) {
wx.saveFile({
tempFilePath: res.tempFilePath,
success:function(res){
that.setData({
imagePath: res.savedFilePath
})
console.log('imagePath', that.data.imagePath)
}
})
},
fail: function (res) {
var downLoadSrc=""
reject(downLoadSrc);
console.log(res);
},
complete: function () {
wx.hideLoading()
ctx = null;
},
}, that);
});
})
})
},
onShareAppMessage: function (res) {
let detailData = wx.getStorageSync('detailsOption');
return {
title: '邀您购买',
imageUrl:this.data.imagePath,
path: '/pages/details/details?id=' + detailData.id + '&groupSn=' + detailData.groupSn + '&thirdSession=' + wx.getStorageSync("thirdSession")
}
},