Voor Niek
by Arjan Haverkamp
JavaScript
// Create 10 random images of same width
// These can also be dataURLs
const imageSrcs = [
'https://picsum.photos/400/200',
'https://picsum.photos/400/230',
'https://picsum.photos/400/100',
'https://picsum.photos/400/300',
'https://picsum.photos/400/400',
'https://picsum.photos/400/120',
'https://picsum.photos/400/300',
'https://picsum.photos/400/200',
'https://picsum.photos/400/140',
'https://picsum.photos/400/222',
];
const loadImage = (src) => new Promise((resolve) => {
const img = new Image();
img.crossOrigin = 'Anonymous'; // Niek: you can skip this line, is to avoid tainting issues with remote images (picsum.photos)
img.onload = () => resolve(img);
img.src = src;
});
const glueImages = async (imgUrls, maxWidth = null) => {
const images = await Promise.all(imageSrcs.map(loadImage));
let width = images[0].naturalWidth, height = 0, factor = 1;
if (null !== maxWidth && width > maxWidth) {
factor = maxWidth / width;
width = maxWidth;
}
for (let img of images) {
height += img.naturalHeight * factor;
}
const canvas = document.createElement('canvas'), ctx = canvas.getContext('2d');
canvas.width = width;
canvas.height = height;
let top = 0;
for (let img of images) {
ctx.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight, 0, top, width, img.naturalHeight * factor);
top += img.naturalHeight * factor;
}
return canvas;
}
(async () => {
const canvas = await glueImages(imageSrcs, 200);
// Convert canvas to image:
const image = new Image();
image.onload = () => {
document.body.appendChild(image);
}
image.src = canvas.toDataURL("image/jpeg");
})();