function createEmptyImage(width, height) { const canvas = document.createElement('CANVAS'); canvas.width = width; canvas.height = height; return canvas.toDataURL(); } function createEl(tag, classes) { const el = document.createElement(tag); if (typeof classes === 'string') { el.classList.add(classes); } else if (Array.isArray(classes)) { el.classList.add(...classes); } return el; } function clearChildNodes(el) { while (el.childNodes.length > 0) { el.removeChild(el.childNodes[0]); } } function initCarousel() { const carousels = document.querySelectorAll('.carousel'); carousels.forEach(carousel => { const images = carousel.querySelectorAll('img'); carousel.classList.add('carousel-ready'); const empty = new Image(); empty.src = createEmptyImage(16, 9); const sizer = createEl('DIV', 'sizer'); sizer.append(empty); const content = createEl('DIV', 'content'); const moving = createEl('DIV', 'moving'); const navigation = createEl('DIV', 'navigation'); const left = createEl('DIV', 'left'); const center = createEl('DIV', 'center'); const right = createEl('DIV', 'right'); navigation.append(left, center, right); clearChildNodes(carousel); carousel.append(sizer, navigation, content, moving); const n = images.length; var current = 0; var animateTo = 0; content.append(images[0]); const idleAction = 'idle'; const movingAction = 'moving'; var ticks = 0; var action = idleAction; const switchTo = a => { action = a; ticks = 0; } setInterval(() => { ticks += 1; if (action === idleAction) { if (ticks > 160) { switchTo(movingAction); animateTo = (current + 1) % n; moving.append(images[animateTo]); moving.classList.add('sliding'); content.classList.add('sliding'); } } else if (action === movingAction) { if (ticks > 84) { switchTo(idleAction); clearChildNodes(content); content.append(images[animateTo]); content.classList.remove('sliding'); clearChildNodes(moving); moving.classList.remove('sliding'); current = animateTo; } } }, 25); }); } initCarousel();