因为网络图片加载是异步的,要保证图片加载后执行图像绘制。使用uni.getImageInfo转换网络图片为临时图片,如需保存海报必须传入上下文ctx的this,否则会报错:canvasToTempFilePath: fail canvas is empty , 报这个错是因为调取 uni.canvasToTempFilePath 接口获取不到canvas
const ctx = uni.createCanvasContext("myCanvas", this);
...
// 绘制用户头像
if (
this.userInfo &&
this.userInfo.user &&
this.userInfo.user.headimgurl
) {
const [err, res] = await uni.getImageInfo({
src: this.userInfo.user.headimgurl,
});
console.log("res", err, res);
}
...
ctx.draw();
this.canvasInstance = this;
uni.canvasToTempFilePath(
{
canvasId: "myCanvas",
success: function (res) {
console.log(res);
uni.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success: function () {
uni.showToast({
title: "保存成功!",
icon: "success",
});
},
fail: function () {
uni.showToast({
icon: "error",
title: "保存失败!",
});
},
});
},
fail: function (err) {
console.log(err);
},
},
this.canvasInstance
);