JSFiddle - React, Tailwind, and code Playground
HTML
<canvas width="500" height="500"></canvas>
CSS
canvas {
background: white;
}
JavaScript
function preloadImage(source) {
return new Promise((resolve, reject) => {
const image = new Image();
image.addEventListener('load', resolve.bind(null, image));
image.src = source;
});
}
function drawImage(context, width, height, itemsPerRow, img, index) {
const x = (index % itemsPerRow) * width;
const y = Math.floor(index / itemsPerRow) * height;
context.drawImage(img, x, y, width, height);
}
function init(canvas, images, delay) {
const context = canvas.getContext('2d');
Promise.all(images.map(preloadImage)).then((imgs) => {
// Recursively draw images
(function draw(index) {
drawImage(context, 100, 100, 5, imgs[index], index);
if (imgs[++index]) {
setTimeout(draw.bind(null, index), delay);
}
}(0));
});
}
const canvas = document.querySelector('canvas');
// An array of 25 image sources
const images = [...Array(25).keys()].map((i) => `http://lorempixel.com/100/100/?${Math.random()}`);
const delay = 50;
init(canvas, images, delay);