两张图片合成,宽度固定,高度根据图片自适应
调用
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);
});
},