一 使用场景:
小程序内,想要分享海报到朋友圈,附带小程序码,达到转发引流的目的。
/**
* 用户点击右上角分享
*/
onShareAppMessage: function() {
},
shareBook: function(e) {
console.log('绘制画布回调函数');
var that = this;
wx.showLoading({
title: '图片生成中...',
})
var res = '';
//调用画图方法
that.drawImages();
},
/**
* 画图方法
*/
drawImages: function() {
let that = this;
// console.log(that.data);
that.canvasHidden = false;
//网络图片地址无法用画布截取到,故使用微信获取图片信息的接口,来设置网络图片地址
console.log(that.data.book.imageUrl);
//二维码图片
var qrcode_image = that.data.codeImg;
//书信息
var title = that.data.book.title;
var author = that.data.book.author;
var summary = that.data.book.summary;
let context = wx.createCanvasContext('imageCanvas', that);
context.setFillStyle('black');
//绘制画布宽高
context.fillRect(0, 0, that.canvasWidth, that.canvasHeight);
context.drawImage(that.data.shareImgSrc, wx.getSystemInfoSync().windowWidth/2-100, 10, 200, 200);
//绘制书籍信息
context.fillText(title, 20, 230)
context.setFontSize(10)
context.fillText("作者:"+author, 20, 250)
context.fillText("书籍简介:", 20, 270)
this.drawText(context, summary, 20, 290, 150, wx.getSystemInfoSync().windowWidth-50);
//绘制二维码图 x y width height
console.log(that.canvasCodeImgY);
context.drawImage(qrcode_image, 20, wx.getSystemInfoSync().windowHeight-150, 130, 130);
context.fillText("长按识别-识别小程序码", 160, wx.getSystemInfoSync().windowHeight - 85, 130, 130);
context.draw(false, that.drawCallBack);
},
drawText(ctx, str, leftWidth, initHeight, titleHeight, canvasWidth) {
var lineWidth = 0;
var lastSubStrIndex = 0; //每次开始截取的字符串的索引
for (let i = 0; i < str.length; i++) {
lineWidth += ctx.measureText(str[i]).width;
if (lineWidth > canvasWidth) {
ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight); //绘制截取部分
initHeight += 20; //16为字体的高度
lineWidth = 0;
lastSubStrIndex = i;
titleHeight += 14;
}
if (i == str.length - 1) { //绘制剩余部分
ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);
}
} // 标题border-bottom 线距顶部距离
titleHeight = titleHeight + 10;
return titleHeight
},
/**
* 绘制画布回调函数
*/
drawCallBack: function() {
var that = this
console.log('绘制画布回调函数');
wx.canvasToTempFilePath({
canvasId: 'imageCanvas',
fileType: 'jpg',
success: function(res) {
var shareImg = res.tempFilePath;
console.log(shareImg)
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success(res) {
wx.hideLoading();
wx.showToast({
title: '保存成功',
icon: 'success',
duration: 2000
});
},
})
},
fail: function(res) {
cosole.log(res, '<-fail res')
}
})
},
注意:
1.网络图片真机上是不可以直接画到画布上去的,要先本地缓存。
2.网络图片缓存必须是https
3.开发过程中 ,小伙伴可能会遇到,模拟器上图片绘制没问题,但是真机上却画不上去,处理办法就是去小程序后台添加域名
4.有其他问题,欢迎留言,祝各位没有遇到这些奇葩问题,