给在线盖章图绘制成图片保存本地

最近做一个微信小程序开电子发票并下载保存本地一个功能

当盖章图是本地图片,绘制发票保存是可以连同图片一起绘制保存本地的

但是当图片是接口拿的一个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);
							}
						});
					});

记录一下~

相关推荐
李少兄1 天前
Notepad++ 全面快捷键指南(2025 最新版)
notepad++
TiAmo zhang2 天前
微信小程序开发案例 | 通讯录小程序(下)
小程序·notepad++
TiAmo zhang3 天前
微信小程序开发案例 | 通讯录小程序(上)
微信小程序·小程序·notepad++
奶糖 肥晨9 天前
微信小程序隐藏滚动条多种方法教程
微信小程序·小程序·notepad++
木易 士心14 天前
组织架构树形选择组件使用说明(Vue3 + UniApp)
微信小程序·钉钉·notepad++
鸭鸭梨吖16 天前
微信小程序输入框---模糊搜索
微信小程序·小程序·notepad++
九皇叔叔21 天前
Windows用Notepad++编辑Shell脚本:一招解决Linux执行报错问题
linux·windows·notepad++
郑叔敲代码22 天前
帝国cms 微信小程序的登录逻辑
微信小程序·小程序·notepad++
white-persist1 个月前
Burp Suite模拟器抓包全攻略
前端·网络·安全·web安全·notepad++·原型模式