You can edit the below JavaScript code to customize the image tool.
Apply Changes
async function processImage(originalImg, secondImageUrl = "", mergeDirection = "horizontal", alignment = "center", gap = 0, bgColor = "transparent") {
// Sanitize parameters
mergeDirection = String(mergeDirection).toLowerCase() === "vertical" ? "vertical" : "horizontal";
alignment = ["start", "center", "end"].includes(String(alignment).toLowerCase()) ? String(alignment).toLowerCase() : "center";
gap = Math.max(0, parseInt(gap) || 0);
bgColor = String(bgColor);
// Load second image if provided as string (URL/Base64), otherwise fallback to the original image
let secondImg = originalImg;
if (secondImageUrl && typeof secondImageUrl === 'string') {
const loadedImg = await new Promise((resolve) => {
const img = new Image();
img.crossOrigin = "Anonymous";
img.onload = () => resolve(img);
img.onerror = () => resolve(null);
img.src = secondImageUrl;
});
if (loadedImg) {
secondImg = loadedImg;
}
}
// Set up canvas
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
let canvasWidth, canvasHeight;
// Calculate dimensions based on merge direction
if (mergeDirection === "horizontal") {
canvasWidth = originalImg.width + secondImg.width + gap;
canvasHeight = Math.max(originalImg.height, secondImg.height);
} else {
canvasWidth = Math.max(originalImg.width, secondImg.width);
canvasHeight = originalImg.height + secondImg.height + gap;
}
canvas.width = canvasWidth;
canvas.height = canvasHeight;
// Fill background if not transparent
if (bgColor !== "transparent") {
ctx.fillStyle = bgColor;
ctx.fillRect(0, 0, canvasWidth, canvasHeight);
} // Otherwise leave it as default transparent
// Helper to calculate alignment offset
function getOffset(maxDim, imgDim, align) {
if (align === "center") return (maxDim - imgDim) / 2;
if (align === "end") return maxDim - imgDim;
return 0; // Assumes "start"
}
// Draw images
if (mergeDirection === "horizontal") {
const y1 = getOffset(canvasHeight, originalImg.height, alignment);
ctx.drawImage(originalImg, 0, y1, originalImg.width, originalImg.height);
const y2 = getOffset(canvasHeight, secondImg.height, alignment);
ctx.drawImage(secondImg, originalImg.width + gap, y2, secondImg.width, secondImg.height);
} else {
const x1 = getOffset(canvasWidth, originalImg.width, alignment);
ctx.drawImage(originalImg, x1, 0, originalImg.width, originalImg.height);
const x2 = getOffset(canvasWidth, secondImg.width, alignment);
ctx.drawImage(secondImg, x2, originalImg.height + gap, secondImg.width, secondImg.height);
}
return canvas;
}
Apply Changes