先看下效果图
生成海报后,点击保存到相册,会调起请求权限,是否同学调用我们的相册,允许之后,这张海报就会自动存入我们的相册
具体实现:
<view class='canvas-box' v-show='visible'>
<canvas id='canvas' class='canvas' canvas-id="firstCanvas">
</canvas>
<cover-view class='btn' @click='savePoster'>点击此处保存到相册</cover-view>
</view>
下面就是逻辑代码了
data
data() {
return {
card: {}, //后台返回的数据
visible: false, //控制海报是否隐藏
wx_qrcode:'', //小程序二维码
customData: {
ctx: null,
},
}
},
绘制海报
drawPoster() {
let _ = this;
this.customData.ctx = wx.createCanvasContext('firstCanvas');
// 获取画布的宽高
uni.createSelectorQuery().select('#canvas').boundingClientRect(function(rect) {
let canvasWidth = rect.width;
let canvasHeight = rect.height;
// 清除画布
_.customData.ctx.clearRect(0, 0, canvasWidth, canvasHeight);
// 绘制背景
_.customData.ctx.rect(0, 0, canvasWidth, canvasHeight);
_.customData.ctx.setFillStyle('white');
_.customData.ctx.fill();
wx.getImageInfo({
src: _.wx_qrcode,
success(res) {
// // 绘制海报
let posterHeight = canvasHeight - 100; // 海报高度
let posterWidth = res.width;
let offsetX = (canvasWidth - posterWidth) / 2;
_.customData.ctx.drawImage(res.path,-100, -70, canvasWidth+100, posterWidth+200, 0, 0, posterWidth,
300);
// 绘制文字
_.customData.ctx.setFillStyle('#31312E');
_.customData.ctx.setFontSize(14);
if(JSON.stringify(_.card)!==''){
console.log('执行了')
_.customData.ctx.fillText(_.card.company, 15, posterHeight + 41);
_.customData.ctx.fillText(_.card.real_name, 35, posterHeight + 71);
}
// 绘制二维码
wx.getImageInfo({
src:_.card.head_img,
success(res) {
_.customData.ctx.drawImage(res.path, 0, 0, res.width, res.height, canvasWidth - 80 - 10,
posterHeight + 10, 80, 80);
_.customData.ctx.draw();
}
});
// 绘制按钮
}
})
}).exec();
},
将海报存入相册
doSave() {
wx.canvasToTempFilePath({
x: 0,
y: 0,
canvasId: 'firstCanvas',
success(res) {
console.log(res)
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success(res) {
wx.showToast({
title: '保存成功',
})
},
fail(err) {
wx.showToast({
title: '请授权',
icon: 'none',
})
}
})
},
fail(err) {
wx.showToast({
title: '保存失败',
})
},
})
},
保存海报
savePoster() {
let _ = this;
wx.getSetting({
success(res) {
// 查询用户是否授权
if (res.authSetting['scope.writePhotosAlbum']) {
_.doSave();
}else {
wx.authorize({
scope: 'scope.writePhotosAlbum',
success() {
_.doSave();
},
fail() {
// wx.navigateTo({
// url: '/pages/logs/logs',
// })
uni.showToast({
title:'没有',
})
}
})
}
}
})
},
调用的点击事件
shareAround() {
this.visible = true
// setTimeout(()
setTimeout(()=>{
this.drawPoster()
},1000)
// )
},
在这个地方提醒一下,如果是到真机或者线上的话,一定要把我们这个图片地址在微信公众平台里面的downloadFile合法域名加上去