项目有个需求:代言人模块分享出去时。需要合成几张图片作为一张海报分享出去
需要用到canvas组件,组件的部分合成图需要下载下来,所以后端要配置好下载合法域名如下图,配置ok后开发者工具会看到合法域名
代码逻辑
1、点击分享弹框出现,点击生成海报调用图片下载api,保存合成海报图(canvas合成的图是用tempFilePath路径)
saveImage: function() {
wx.showLoading({
title: ‘海报生成中…’
});
let self = this;
const ctx = wx.createCanvasContext(‘myCanvas’);
var CompnayName = self.data.spokesmanSet.name;
var userName = self.data.userName;
ctx.setFillStyle(‘white’)
ctx.fillRect(0, 0, 276, 444)
wx.downloadFile({
url: self.data.spokesmanSet.imageUrlFull, //海报
success: function(res) {
let post = res.tempFilePath
wx.downloadFile({
url: self.data.headImageUrlFull, //个人logo
success: function(res) {
let logo = res.tempFilePath
wx.downloadFile({
url: self.data.memberSpokesman.spokesImageUrlFull, //二维码
success: function(res) {
let code = res.tempFilePath
wx.hideLoading();
ctx.drawImage(post, 0, 0, 276, 155);
ctx.fillStyle = “#fff”;
ctx.fillRect(117.5, 136, 41, 41);
ctx.drawImage(logo, 119.5, 138, 37, 37);
ctx.drawImage(code, 65, 240, 134, 120);
ctx.setFontSize(12)
ctx.setFillStyle(’#333’);
ctx.fillText(userName, (276 - ctx.measureText(userName).width) / 2, 195)
ctx.setFontSize(12)
ctx.setFillStyle(’#fb5e2c’);
ctx.fillText(CompnayName, (276 - ctx.measureText(CompnayName+’ 代言人’).width) / 2, 215)
//色块位置
var left = ctx.measureText(CompnayName + ’ ‘).width + (276 - ctx.measureText(CompnayName +’ 代言人’).width) / 2
ctx.fillStyle = “#fb5e2c”;
ctx.fillRect(left, 204, 40, 13);
//代言人文字位置
ctx.setFontSize(12)
ctx.setFillStyle(’#fff’);
ctx.fillText(‘代言人’,left+2, 215)
//长按识别打开小程序文字位置
ctx.setFontSize(12)
ctx.setFillStyle(’#333’);
ctx.fillText(‘长按识别打开小程序’, (276 - ctx.measureText(‘长按识别打开小程序’).width) / 2, 400)
ctx.draw(false, function(e) {
wx.canvasToTempFilePath({
x: 0,
y: 0,
width: 375,
height: 417,
quality: 1,
canvasId: ‘myCanvas’,
success: function(respon) {
ctx.setFillStyle(‘white’)
self.setData({
logo: respon.tempFilePath,
posterShow: true
})
},
fail: function(res) {
wx.showToast({
title: ‘canvasToTempFilePath—fail’,
icon: ‘none’
})
}
});
});
},
fail: function(res) {
wx.showToast({
title: ‘下载失败,请重新生成’,
icon: ‘none’
})
}
})
},
fail: function(res) {
wx.showToast({
title: ‘头像下载失败,请重新生成’,
icon: ‘none’
})
}
});
},
fail: function(res) {
wx.showToast({
title: ‘下载失败,请重新生成’,
icon: ‘none’
})
}
})
},
2、点击保存到相册时做授权处理
save: function() {
var _this = this;
wx.getSetting({
success(res) {
console.log(res)
if (res.authSetting[‘scope.writePhotosAlbum’] != undefined && res.authSetting[‘scope.writePhotosAlbum’] != true) {
wx.showModal({
title: ‘提示’,
content: ‘您未授权保存到相册,确认授权?’,
success: function (res) {
if (res.confirm) {
wx.openSetting({
success: function (res) {
if (res.authSetting[“scope.writePhotosAlbum”] == true) {
} else {
}
}
})
}
}
})
} else {
wx.saveImageToPhotosAlbum({
filePath: _this.data.logo,
success(res) {
console.log(‘保存成功—ok’)
wx.showToast({
title: ‘保存成功’,
icon: ‘none’
})
}
})
}
},
fail: function(e) {
console.log(999)
}
});
},
注意点:canvas海报合成的单位是px,小程序用的是rpx
|
请发表评论