将用户名称,头像,小程序二维码(base64)绘制到画布中并保存
1.将一张底图打底
2,文字,头像的布局;将base64格式的二维码转成本地临时文件;
3.canvas生成图片
4.将图片保存至相册
具体代码如下:
view
立即邀请
js:
invitian(name,headImg,code){
uni.showLoading({title: '图片合成中',mask:true, })
wx.getImageInfo({
src: 'https://source1.suddenfix.com/ask_share_v6.png',
success:res=>{
console.log(res)
const ctx = wx.createCanvasContext('shareCanvas');
ctx.save();
ctx.drawImage(res.path, 0, 0, 375, 667)
ctx.setFillStyle('#909399') // 文字颜色:黑色
ctx.setFontSize(12) // 文字字号:22px
ctx.fillText(name+':', 39, 570);
ctx.save();
ctx.setFillStyle('#000') // 文字颜色:黑色
ctx.setFontSize(12) // 文字字号:22px
ctx.fillText('送你一份120元修机红包', 39, 586);
ctx.save();
ctx.setFillStyle('#000') // 文字颜色:黑色
ctx.setFontSize(12) // 文字字号:22px
ctx.fillText('及价值99元的钢化膜免费换新资格', 39, 606);
ctx.save();
const buffer = wx.base64ToArrayBuffer(code);
// console.log("buffer:"+buffer);
let fileManager = wx.getFileSystemManager();//获取文件管理器
let filePath = wx.env.USER_DATA_PATH + '/qrCode.jpg';//设置临时路径
fileManager.writeFile({//获取到的数据写入临时路径
filePath: filePath,//临时路径
encoding: 'binary',//编码方式,二进制
data: buffer,//请求到的数据
success: codeRes=>{
// console.log("filePath:"+filePath);
wx.getImageInfo({
src: filePath,
success:res=>{
// console.log(res.path)
ctx.save();
ctx.drawImage(res.path, 236,546, 102, 102);
wx.getImageInfo({
src: headImg,
success:res=>{
// console.log(res.path)
ctx.save();
ctx.beginPath();
ctx.arc(60,531, 21, 0, 2 * Math.PI);
ctx.clip();
ctx.drawImage(res.path,39,510,42,42);
ctx.restore();
ctx.draw(false,()=>{
wx.canvasToTempFilePath({
x: 0,
y: 0,
width: 375,
height: 667,
destWidth: 750,
destHeight: 1334,
canvasId: 'shareCanvas',
quality:1,
success: res=>{
// console.log(res.tempFilePath)
uni.hideLoading();
this.pathUrl = res.tempFilePath;
let eTime = Date.parse(new Date());
wx.setStorageSync("sdfPosterTempFilePath",res.tempFilePath);
wx.setStorageSync("data_expiration",eTime);
this.shareCanvasShow = true;
},
fail:err=>{
uni.hideLoading() ;
}
})
});
},
fail:err=>{
uni.hideLoading() ;
}
})
},
fail:err=>{
uni.hideLoading() ;
}
})
},
fail: function(res) {
uni.hideLoading() ;
},
})
},
fail:err=>{
uni.hideLoading() ;
}
})
}
这里使用到了:二维码是base64格式,使用base64ToArrayBuffer转成buffer;
再利用getFileSystemManager拿到本地临时文件画到画布中;
这里可以是用( Promise.all())
我这个写代码看着实在不雅
一个保存海报的操作:
// 保存海报
saveImg(){
uni.showLoading({title: '保存中...',mask:true, })
uni.saveImageToPhotosAlbum({
filePath: this.pathUrl,
success: res=>{
uni.hideLoading() ;
uni.showToast({title: '保存成功', duration: 2000});
},fail:(err)=>{
uni.hideLoading();
uni.showModal({
title: '是否要打开设置页',
content: '请到小程序设置中打开相册授权',
success: res=>{
if (res.confirm) {
this.openSetting();
}
}
});
}
});
},
openSetting(){
uni.openSetting({
success:res=> {
if(res.authSetting['scope.writePhotosAlbum']){
this.saveImg();
}else{
}
}
});
},