使用技术栈:uni-app
使用官方文档提供的API:createCanvasContext(uni-app) /CanvasContext(原生)
*注意:海报里用到的图片都得先使用小程序提供的下载方法把网络图片下载成本地文件才能使用,否则会出现跨域问题!
html代码:
<canvas id="imgCanvas" canvas-id="imgCanvas" style="width: 260px;height:414px;background: #FFFFFF;"></canvas>
js代码:
data(){
return {
imgUrl: '',//生成的海报路径
ewm: '', //小程序码
bg_img: 'https://s3.cn-north-1.amazonaws.com.cn/huivo-miyamibao/png/c3962d3ae80e9847316e0c8d00ebb00f.png', //背景图片
system_info: [], //系统信息(用到头像)
}
}
methods:{
share(){
//分享(生成海报)
//绘图
var that = this;
//这里等promise执行,避免拿不到图片临时路径
//先把我们用到的素材图片下载成本地图片
const promise1 = new Promise((resolve, reject) => {
uni.downloadFile({
url: that.bg_img, //背景图
success: (res) => {
resolve(res)
}
})
});
const promise2 = new Promise((resolve, reject) => {
uni.downloadFile({
url: that.ewm, //小程序码
success: (res) => {
resolve(res)
}
})
});
const promise3 = new Promise((resolve, reject) => {
uni.downloadFile({
url: that.userInfo.avatarUrl, //微信用户头像
success: (res) => {
resolve(res)
}
})
});
Promise.all([promise1, promise2, promise3]).then((values) => {
this.make_canvas(values[0], values[1], values[2]);
});
},
make_canvas(img01, img02, header) {
var ctx = uni.createCanvasContext('imgCanvas') //绑定画布
//drawImage 参数说明:drawImage(图片地址,图片w,图片h,x轴,y轴)
ctx.setFillStyle("#ffffff");
ctx.drawImage(img01.tempFilePath, 0, 0, 260, 414); //填充进图片
ctx.drawImage(img02.tempFilePath, 17, 337, 61, 61); //填充进图片
ctx.drawImage(header.tempFilePath, 92, 280, 23, 23, );
//有几处内容就写几个
ctx.setFillStyle('#FFFFFF') //设置内容1的文字样式
ctx.setFontSize(8);
ctx.fillText(this.userInfo.nickName, 123, 295) //用户微信名称
ctx.setFillStyle('#FFFFFF') //设置内容2的文字样式
ctx.setFontSize(8);
ctx.fillText('为您推荐', 190, 295)
ctx.draw(); //输出到画布中
uni.showLoading({ //增加loading等待效果
mask: true
})
setTimeout(() => { //不加延迟的话,base64有时候会赋予undefined
uni.canvasToTempFilePath({
canvasId: 'imgCanvas',
success: (res) => {
//生成的海报地址
this.imgUrl = res.tempFilePath
}
})
uni.hideLoading();
}, 1200)
},
//保存到相册方法:
downloadFile() {
uni.saveImageToPhotosAlbum({
filePath: this.imgUrl,
success: function() {
console.log('save success');
}
});
},
}
end~~~
如有错误或观点不一致的请评论留言共同讨论,本人前端小白一枚,根据自己实际项目遇到的问题进行总结分享,谢谢大家的阅读!
文章对您有所帮助请给作者点个赞支持下,谢谢~