//HTML
<canvas canvas-id="canvas" style="width:328px;height:232px"></canvas>
//js
//保存图片
//生成img
getCanvasImg() {
wx.showLoading({
title: "图片生成中...", //提示的内容,
mask: true, //显示透明蒙层,防止触摸穿透,
success: res => {
var path = "https://****/****.jpg";
var that = this;
// 服务器相片下载到本地
wx.downloadFile({
url: path,
success(res) {
console.log("downloadFile", res);
if (res.statusCode === 200) {
console.log(res.tempFilePath);
// 生命周期函数--监听页面初次渲染完成
var ctx = wx.createCanvasContext("canvas");
ctx.drawImage(res.tempFilePath, 0, 0, 328, 232);
ctx.setFontSize(9);
ctx.setFillStyle("#333333");
if (that.nickName == null) {
ctx.fillText(
that.getData && that.getData.nickName
? that.getData.nickName + " 同志:"
: "战疫 同志:",
35,
124
);
} else {
ctx.fillText(that.nickName + " 同志:", 35, 124);
}
ctx.fillText(that.bindTime, 235, 205);
ctx.stroke();
ctx.draw(false, res => {
// 生成图片保存本地
wx.canvasToTempFilePath({
canvasId: "canvas",
success(res) {
console.log("canvasToTempFilePath", res);
// 保存到手机相册
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success(res) {
console.log("saveImageToPhotosAlbum", res);
wx.showToast({
title: "保存成功",
icon: "success"
});
},
fail(err) {
console.log("失败保存", err);
wx.showToast({
title: "保存失败", //提示的内容,
icon: "none", //图标,
duration: 2000 //延迟时间,
});
}
});
}
});
});
console.log(ctx);
}
},
fail(err) {
console.log("downloadFile Error:", err);
}
});
}
});
},
//保存图片
saveAlbum() {
let that = this;
// 相册授权
wx.getSetting({
success(res) {
// 进行授权检测,未授权则进行弹层授权
if (!res.authSetting["scope.writePhotosAlbum"]) {
wx.authorize({
scope: "scope.writePhotosAlbum",
success() {
//下载到本地
that.getCanvasImg();
},
// 拒绝授权
fail() {
that.saveAlbumImgOne = false;
that.saveAlbumImgTow = true;
}
});
} else {
// 已授权则直接进行保存图片
that.getCanvasImg();
}
},
fail(res) {
console.log(res);
}
});
},