最近做一个微信小程序开电子发票并下载保存本地一个功能
当盖章图是本地图片,绘制发票保存是可以连同图片一起绘制保存本地的
但是当图片是接口拿的一个https图片在线地址,渲染在页面没问题,但是一旦绘制发票保存本地,就会发现发票上的这个在线地址盖章图片没有绘制成功
因为在线地址需要先使用
uni.downloadFile
把图片下载下来然后进行绘制才能保存下来
javascript
// 绘制合计行
x = margin;
const totalData = ['合计',
`应付:${this.detailInfo.totalActualReceivable}.优惠:${this.detailInfo.totalDiscountAmount}.收款${this.detailInfo.totalReceivedAmount}${this.convertToChinese(this.detailInfo.totalReceivedAmount)}`
];
for (let i = 0; i < totalData.length; i++) {
ctx.fillText(totalData[i], x, y);
x += 450;
}
y += lineHeight;
// 绘制分割线
ctx.beginPath();
ctx.moveTo(margin, y);
ctx.lineTo(800, y);
ctx.stroke();
y += lineHeight;
// 绘制底部说明
ctx.setFontSize(14);
ctx.fillText('*凭本收据可换取正式发票,盖章有效,请妥善保存,遗失不补。', margin, y);
y += lineHeight;
// 绘制备注和收款人
ctx.fillText('备注:-', margin, y);
ctx.fillText(`收款人:${this.detailInfo.cashier}`, 600, y);
y += lineHeight * 2;
if (this.gzimg) {
// 下载网络图片到本地
const downloadRes = await new Promise((resolve, reject) => {
uni.downloadFile({
url: this.gzimg,
success: (res) => {
if (res.statusCode === 200) {
resolve(res.tempFilePath);
} else {
reject(new Error('下载失败'));
}
},
fail: reject
});
});
// 使用本地临时路径绘制
const stampX = 550;
const stampY = y - 200;
const stampSize = 100;
ctx.drawImage(downloadRes, stampX, stampY, stampSize, stampSize);
}
// 绘制完成
ctx.draw(false, () => {
uni.canvasToTempFilePath({
canvasId: 'myCanvas',
success: (res) => {
uni.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success: () => {
uni.showToast({
title: '保存成功',
icon: 'success'
});
},
fail: (err) => {
uni.showToast({
title: '保存失败',
icon: 'none'
});
console.error(err);
}
});
},
fail: (err) => {
console.error('canvas转图片失败', err);
}
});
});
记录一下~