【uniapp】图片合成并导入base64

两张图片合成,宽度固定,高度根据图片自适应

调用

javascript 复制代码
this.mergeImgs(this.imgList).then((res)=>{
	console.log(res,'图片base64')
})

方法

javascript 复制代码
mergeImgs(imgList) {
				// 图片合成
				return new Promise((resolve, reject) => {
					Promise.all(this.fileDtoList.map(imgList)).then((images) => {
						const canvas = document.createElement('canvas')
						const ctx = canvas.getContext('2d')
						// 确定合成图片的宽度
						const maxWidth = 1000; // 设置期望的宽度
						// 计算合成图片的高度
						const totalHeight = images.reduce((total, img) => {
						  const aspectRatio = img.width / img.height;
						  const scaledHeight = maxWidth / aspectRatio;
						  return total + scaledHeight;
						}, 0);
				
						// 设置 canvas 的大小
						canvas.width = maxWidth;
						canvas.height = totalHeight;
				
						// 在 canvas 上绘制图片
						let currentY = 0;
						images.forEach(image => {
						  const aspectRatio = image.width / image.height;
						  const scaledHeight = maxWidth / aspectRatio;
						  ctx.drawImage(image, 0, currentY, maxWidth, scaledHeight);
						  currentY += scaledHeight;
						});
						const base64 = canvas.toDataURL('image/png')
						resolve(base64)
					})
				})
			},
			loadImage(url) {
				return new Promise((resolve, reject) => {
					const image = new Image();
					image.onerror = reject;
					image.src = url;
					image.crossOrigin = 'Anonymous'
					image.onload = () => resolve(image);
				});
			},
相关推荐
tedcloud1234 小时前
RTK部署教程:构建稳定的AI Workflow环境
服务器·javascript·人工智能·typescript·ocr
ZC跨境爬虫5 小时前
跟着 MDN 学CSS day_16:(深入掌握背景与边框的艺术)
前端·css·ui·html·tensorflow
遗憾随她而去.5 小时前
uniapp App平台 真机运行
uni-app
愚者Pro7 小时前
Flutter Widget组件学习(专为 Uniapp 转 Flutter 定制)
vue.js·学习·flutter·uni-app
道里7 小时前
花了 5 万刀用 AI 写代码之后,这是我的全部经验
前端·人工智能
Royzst8 小时前
xml知识点
java·服务器·前端
IT_陈寒8 小时前
React useEffect闭包陷阱差点把我整失业了
前端·人工智能·后端
kyriewen9 小时前
推行AI写代码一年后,Code Review变成了新的加班理由
前端·ai编程·cursor
前端环境观察室9 小时前
给 Agent Browser Workflow 加一层可观测性:Trace、Snapshot 和 Review Queue
前端
柒瑞9 小时前
Superpowers结合Claude code浅实战
前端