运行环境 微信小程序
<template>
<div>
<canvas id="myCanvas" canvas-id="myCanvas" canvas-type="2d"
:style="{ height: '1400rpx', width: '650rpx', background: '#FFFFFF', border: '1rpx solid red', opacity: 0, position: 'absolute', left: '1500rpx' }"></canvas>
</div>
</template>
export default {
data() {
return {
ctx: null,
}
},
mounted() {
this.ctx = uni.createCanvasContext('myCanvas');
},
}
saveImageToPhotosAlbum() {
// 下载图片并保存到相册
let that = this
const ctx = wx.createCanvasContext('myCanvas')
uni.showLoading({
title: '海报绘制中'
});
Promise.all([
new Promise((resolve, reject) => {
uni.getImageInfo({
src: "你的图片",
success: (response) => resolve(response),
fail: (error) => reject(error)
});
}),
new Promise((resolve, reject) => {
uni.getImageInfo({
src: "你的图片",
success: (response) => resolve(response),
fail: (error) => reject(error)
});
})
]).then(([backgroundImage, logoImage]) => {
// 绘制背景和logo
const ctx = wx.createCanvasContext('myCanvas');
ctx.clearRect(0, 0, 375, 512);
// 绘制背景
ctx.fillStyle = "#fff";
ctx.fillRect(0, 0, 375, 512);
ctx.drawImage(backgroundImage.path, 0, 0, 350, 730); // 画背景图
// 绘制logo
ctx.drawImage(logoImage.path, 220, 280, 40, 40); // 绘制logo
// 设置文字内容
ctx.fillStyle = '#006C7A';
ctx.setFontSize(8);
ctx.fillText(that.datainfo.resultData.clientName, 130, 232);
ctx.fillText(that.datainfo.resultData.joinDate, 130, 276);
ctx.fillText(that.datainfo.resultData.clientIdentity, 130, 320);
ctx.stroke();
ctx.save();
ctx.draw(true, () => {
setTimeout(() => {
wx.canvasToTempFilePath({
destWidth: 750,
destHeight: 1420,
canvasId: 'myCanvas',
success: function (res) {
console.log("save ok canvasToTempFilePath", res);
var tempFilePath = res.tempFilePath;
wx.saveImageToPhotosAlbum({
filePath: tempFilePath,
success(res) {
uni.hideLoading();
console.log(
'saveImageToPhotosAlbum',
res);
uni.showToast({
title: '已保存到相册',
icon: 'success',
duration: 2000
});
},
fail: function (err) {
uni.hideLoading();
uni.showToast({
title: '请稍后重试',
icon: 'none',
duration: 2000
});
console.error(
'saveImageToPhotosAlbum failed',
err);
}
});
},
fail: function (err) {
console.error('canvasToTempFilePath failed', err);
}
});
}, 500);
});
}).catch((error) => {
console.error("Error loading images:", error);
});
},