You can edit the below JavaScript code to customize the image tool.
Apply Changes
async function processImage(originalImg, img2Src = "", img3Src = "", layout = "horizontal", padding = 10, bgColor = "#ffffff") {
// Helper function to load an image from a source string (URL or Base64)
// If no valid source is provided or loading fails, it falls back to the original image
// to ensure 3 pictures are always represented.
const loadSecondaryImage = (src) => {
return new Promise((resolve) => {
if (!src || typeof src !== 'string' || src.trim() === "") {
resolve(originalImg);
return;
}
const img = new Image();
img.crossOrigin = "Anonymous";
img.onload = () => resolve(img);
img.onerror = () => resolve(originalImg);
img.src = src;
});
};
// Load the second and third images
const img2 = await loadSecondaryImage(img2Src);
const img3 = await loadSecondaryImage(img3Src);
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
// Clean up numerical parameters
const pad = Math.max(0, parseInt(padding) || 0);
let w1 = originalImg.width;
let h1 = originalImg.height;
let w2, h2, w3, h3;
let totalW = 0;
let totalH = 0;
// Layout configuration logic
if (layout === "vertical") {
// Vertically stack photos: Scale img2 & img3 to match originalImg's width
w2 = w1;
h2 = img2.height * (w1 / img2.width);
w3 = w1;
h3 = img3.height * (w1 / img3.width);
totalW = w1 + (pad * 2);
totalH = h1 + h2 + h3 + (pad * 4);
canvas.width = totalW;
canvas.height = totalH;
ctx.fillStyle = bgColor;
ctx.fillRect(0, 0, totalW, totalH);
ctx.drawImage(originalImg, pad, pad, w1, h1);
ctx.drawImage(img2, pad, pad * 2 + h1, w2, h2);
ctx.drawImage(img3, pad, pad * 3 + h1 + h2, w3, h3);
} else if (layout === "grid") {
// Grid setup: 2 photos horizontally on top, 1 large photo scaling underneath
h2 = h1;
w2 = img2.width * (h1 / img2.height);
let topRowWidth = w1 + w2;
// Scale the third image to fit the total width of the top row
w3 = topRowWidth;
h3 = img3.height * (topRowWidth / img3.width);
totalW = topRowWidth + (pad * 3);
totalH = h1 + h3 + (pad * 3);
canvas.width = totalW;
canvas.height = totalH;
ctx.fillStyle = bgColor;
ctx.fillRect(0, 0, totalW, totalH);
// Top row
ctx.drawImage(originalImg, pad, pad, w1, h1);
ctx.drawImage(img2, pad * 2 + w1, pad, w2, h2);
// Bottom row
ctx.drawImage(img3, pad, pad * 2 + h1, w3, h3);
} else {
// Default: horizontally arrange photos (side-by-side)
// Scale img2 & img3 to match originalImg's height
h2 = h1;
w2 = img2.width * (h1 / img2.height);
h3 = h1;
w3 = img3.width * (h1 / img3.height);
totalW = w1 + w2 + w3 + (pad * 4);
totalH = h1 + (pad * 2);
canvas.width = totalW;
canvas.height = totalH;
ctx.fillStyle = bgColor;
ctx.fillRect(0, 0, totalW, totalH);
ctx.drawImage(originalImg, pad, pad, w1, h1);
ctx.drawImage(img2, pad * 2 + w1, pad, w2, h2);
ctx.drawImage(img3, pad * 3 + w1 + w2, pad, w3, h3);
}
return canvas;
}
Apply Changes