You can edit the below JavaScript code to customize the image tool.
Apply Changes
async function processImage(originalImg, secondImageSrc = '', layout = 'horizontal', gap = 10, alignment = 'center', bgColor = '#ffffff') {
return new Promise((resolve) => {
const parsedGap = isNaN(Number(gap)) ? 0 : Number(gap);
function mergeImages(secondImg) {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const w1 = originalImg.width;
const h1 = originalImg.height;
const w2 = secondImg.width;
const h2 = secondImg.height;
if (layout === 'vertical') {
canvas.width = Math.max(w1, w2);
canvas.height = h1 + h2 + parsedGap;
ctx.fillStyle = bgColor;
ctx.fillRect(0, 0, canvas.width, canvas.height);
const x1 = alignment === 'start' ? 0 : alignment === 'end' ? canvas.width - w1 : (canvas.width - w1) / 2;
const x2 = alignment === 'start' ? 0 : alignment === 'end' ? canvas.width - w2 : (canvas.width - w2) / 2;
ctx.drawImage(originalImg, x1, 0);
ctx.drawImage(secondImg, x2, h1 + parsedGap);
} else if (layout === 'blend') {
canvas.width = Math.max(w1, w2);
canvas.height = Math.max(h1, h2);
ctx.fillStyle = bgColor;
ctx.fillRect(0, 0, canvas.width, canvas.height);
const x1 = (canvas.width - w1) / 2;
const y1 = (canvas.height - h1) / 2;
ctx.drawImage(originalImg, x1, y1);
const x2 = (canvas.width - w2) / 2;
const y2 = (canvas.height - h2) / 2;
ctx.globalAlpha = 0.5;
ctx.drawImage(secondImg, x2, y2);
ctx.globalAlpha = 1.0;
} else if (layout === 'pip') { // Picture-in-picture
canvas.width = w1;
canvas.height = h1;
ctx.fillStyle = bgColor;
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(originalImg, 0, 0);
const pipWidth = canvas.width * 0.25;
const ratio = pipWidth / w2;
const pipHeight = Math.max(1, h2 * ratio);
const padding = parsedGap;
ctx.drawImage(secondImg, canvas.width - pipWidth - padding, canvas.height - pipHeight - padding, pipWidth, pipHeight);
} else { // Defaults to 'horizontal' side-by-side
canvas.width = w1 + w2 + parsedGap;
canvas.height = Math.max(h1, h2);
ctx.fillStyle = bgColor;
ctx.fillRect(0, 0, canvas.width, canvas.height);
const y1 = alignment === 'start' ? 0 : alignment === 'end' ? canvas.height - h1 : (canvas.height - h1) / 2;
const y2 = alignment === 'start' ? 0 : alignment === 'end' ? canvas.height - h2 : (canvas.height - h2) / 2;
ctx.drawImage(originalImg, 0, y1);
ctx.drawImage(secondImg, w1 + parsedGap, y2);
}
resolve(canvas);
}
if (!secondImageSrc) {
// Uses original image as a duplicate for demonstration if no second image URL is provided
mergeImages(originalImg);
} else {
const img2 = new Image();
img2.crossOrigin = 'Anonymous';
img2.onload = () => mergeImages(img2);
// Fallback to merge duplicate original instance if external URL fails
img2.onerror = () => mergeImages(originalImg);
img2.src = secondImageSrc;
}
});
}
Apply Changes