【uniapp】图片合成并导入base64

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

调用

this.mergeImgs(this.imgList).then((res)=>{
	console.log(res,'图片base64')
})

方法

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);
				});
			},

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值