小程序的分享有自己的机制,在页面点击右上角,或者页面中的button 采用open-type=share方式也可以触发onShareAppMessage方法。
文档里面明确说明,分享的图片可以采用网络图片,那么我们自定义图片之后将其保存,得到微信的临时文件路径也是符合要求的。
废话不多说,直接贴代码。我将绘制分享图的功能封装了一下,如下:
// 考虑了有些文字是带有换行符的,安卓和iOS对于换行符的处理不一样,所以这里需要单独考虑
// canvas绘制文字自动换行
function fillTextToCanvas(cxt, text, beginWidth, beginHeight) {
const lineLength = 24;// 行高
let item = '';
let count = 0;
const stringLength = text.length;
const newText = text.split('');
const context = cxt;
let beginHeightNew = beginHeight;
context.textAlign = 'left';
for (let i = 0; i <= stringLength; i++) {
if (count === 15) { // count一行显示多少个字
context.fillText(item, beginWidth, beginHeightNew);
beginHeightNew += lineLength;
item = '';
count = 0;
}
if (i === stringLength) {
context.fillText(item, beginWidth, beginHeightNew);
item = '';
count = 0;
}
item += newText[0];
count += 1;
newText.shift();
}
}
// canvas绘制文