Image Sequence on Scroll

Category: Video & Audio. Last updated: Aug 20, 2025

Setup — External Scripts

Setup: External Scripts
html
<script src="https://cdn.jsdelivr.net/npm/gsap@3.14.1/dist/gsap.min.js"></script>
CDN 2
html
<script src="https://cdn.jsdelivr.net/npm/gsap@3.14.1/dist/ScrollTrigger.min.js"></script>

Code

index.html
html
<div data-sequence-wrap data-scroll-end="bottom top" data-scroll-start="top top" class="image-sequence__wrap">
  <div class="image-sequence__sticky">
    <div data-sequence-element class="image-sequence__element">
      <canvas data-sequence-canvas 
              data-desktop-src="https://osmo.b-cdn.net/resource-media/image-sequence-demo/desktop/highres" 
              data-mobile-src="https://osmo.b-cdn.net/resource-media/image-sequence-demo/mobile/mobile" 
              data-static-src="https://osmo.b-cdn.net/resource-media/image-sequence-demo/desktop/highres000.webp" 
              data-filetype="webp" 
              data-frames="120" 
              data-digits="3" 
              data-index-start="0" 
              class="image-sequence__canvas">
      </canvas>
    </div>
  </div>
</div>
styles.css
css
.image-sequence__wrap {
  width: 100%;
  height: 300vh;
  position: relative;
}

.image-sequence__sticky {
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100vh;
  display: flex;
  position: sticky;
  top: 0;
}

.image-sequence__element {
  z-index: 0;
  width: 100%;
  height: 100%;
  position: absolute;
  inset: 0%;
}

.image-sequence__canvas {
  width: 100%;
  height: 100%;
  padding: 0;
  position: relative;
}
script.js
javascript
function initImageSequenceScroll() {
  const wraps = document.querySelectorAll('[data-sequence-wrap]');
  
  wraps.forEach((wrap) => {
    // Prevent double-initializing
    if (wrap.dataset.sequenceInit === 'true') return;
    wrap.dataset.sequenceInit = 'true';

    const element = wrap.querySelector('[data-sequence-element]');
    const canvas = element && element.querySelector('[data-sequence-canvas]');
    if (!element || !canvas) return;
    
    // Data attributes and their fallbacks
    const frames = parseInt(canvas.dataset.frames, 10) || 1;
    const digits = parseInt(canvas.dataset.digits, 10) || 3;
    const indexStart = parseInt(canvas.dataset.indexStart, 10) || 0;
    const desktopSrc = canvas.dataset.desktopSrc || '';
    const mobileSrc = canvas.dataset.mobileSrc || desktopSrc;
    const staticSrc = canvas.dataset.staticSrc;
    const filetype = canvas.dataset.filetype || 'webp';
    const startTrigger = wrap.dataset.scrollStart || 'top top';
    const endTrigger = wrap.dataset.scrollEnd || 'bottom top';
    const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

    const isMobile = window.matchMedia('(max-width: 767px)').matches;
    const baseUrl = isMobile ? mobileSrc : desktopSrc;
    const lastIndex = indexStart + frames - 1;

    // Track last rendered scroll progress so we can redraw on resize
    let lastProgress = 0;

    // Canvas setup (size to the sticky element)
    const ctx = canvas.getContext('2d');
    function resizeCanvas() {
      const dpr = window.devicePixelRatio || 1;
      const width = element.clientWidth;
      const height = element.clientHeight;
      if (canvas.width !== width * dpr || canvas.height !== height * dpr) {
        canvas.width = width * dpr;
        canvas.height = height * dpr;
        canvas.style.width = `${width}px`;
        canvas.style.height = `${height}px`;
      }
    }
    resizeCanvas();

    // Image cache and loading queue
    const loaded = new Map();
    const queue = [];
    let processingQueue = false;
    let resizeTimer;

    // Draw helper (canvas equivalent of object-fit: cover)
    function drawCover(img) {
      if (!img) return;
      resizeCanvas();
      const canvasWidth = canvas.width;
      const canvasHeight = canvas.height;
      const scale = Math.max(canvasWidth / img.width, canvasHeight / img.height);
      const x = (canvasWidth - img.width * scale) / 2;
      const y = (canvasHeight - img.height * scale) / 2;
      ctx.clearRect(0, 0, canvasWidth, canvasHeight);
      ctx.drawImage(img, x, y, img.width * scale, img.height * scale);
    }

    window.addEventListener('resize', () => {
      clearTimeout(resizeTimer);
      resizeTimer = setTimeout(() => {
        resizeCanvas();
        if (loaded.size) render(lastProgress);
        ScrollTrigger.refresh();
      }, 200);
    });

    function pad(num) {
      return String(num).padStart(digits, '0');
    }
    
    function getUrl(i) {
      return `${baseUrl}${pad(i)}.${filetype}`;
    }
    
    function loadFrame(i, onDone) {
      if (loaded.has(i) || i < indexStart || i > lastIndex) return;
      const img = new Image();
      img.src = getUrl(i);

      img.onload = () => {
        loaded.set(i, img);
        if (typeof onDone === 'function') onDone();
      };

      // Log when a frame is missing or fails to load
      img.onerror = () => {
        console.warn('[ImageSequence] Failed to load frame', {
          index: i,
          url,
          wrap: wrap
        });
      };
    }

    // Daybreak-style progressive loader (binary midpoint / "wave" fill)
    function processQueue() {
      if (processingQueue) return;
      const next = queue.shift();
      if (!next) return;
      processingQueue = true;
      const [a, b] = next;
      if (b - a <= 1) {
        processingQueue = false;
        processQueue();
        return;
      }
      const m = Math.floor((a + b) / 2);
      loadFrame(m, () => {
        queue.push([a, m], [m, b]);
        processingQueue = false;
        setTimeout(processQueue, 0);
      });
    }
    
    function startLoading() {
      loadFrame(indexStart, () => {
        drawImageAt(indexStart); // Show the first frame right away
        loadFrame(lastIndex); // Preload the last frame
        queue.push([indexStart, lastIndex]);
        processQueue();
        ScrollTrigger.refresh();
      });
    }
    
    function findNearestLoaded(i) {
      for (let r = 1; r <= 10; r++) {
        if (loaded.has(i - r)) return i - r;
        if (loaded.has(i + r)) return i + r;
      }

      const keys = Array.from(loaded.keys());
      if (keys.length === 0) return null;
      let nearest = keys[0];
      let minDiff = Math.abs(i - nearest);
      for (const k of keys) {
        const diff = Math.abs(i - k);
        if (diff < minDiff) {
          nearest = k;
          minDiff = diff;
        }
      }
      return nearest;
    }
    
    function drawImageAt(i) {
      const img = loaded.get(i);
      if (!img) return;
      drawCover(img);
    }
    
    function render(progress) {
      const relative = progress * (frames - 1);
      const index = indexStart + Math.round(relative);
      if (loaded.has(index)) {
        drawImageAt(index);
      } else {
        const nearest = findNearestLoaded(index);
        if (nearest !== null) drawImageAt(nearest);
      }
    }

    // Reduced motion: draw a single static image (or first frame fallback)
    if (reduceMotion) {
      if (staticSrc) {
        const staticImage = new Image();
        staticImage.src = staticSrc;
        staticImage.onload = () => {
          drawCover(staticImage);
        };
        staticImage.onerror = () => {};
        return;
      }
      loadFrame(indexStart, () => {
        drawImageAt(indexStart);
      });
      return;
    }
    
    // Begin loading frames in the background
    startLoading();
    
    // Set up ScrollTrigger
    const st = ScrollTrigger.create({
      trigger: wrap,
      start: startTrigger,
      end: endTrigger,
      scrub: true,
      onUpdate: (self) => {
        lastProgress = self.progress;
        render(self.progress);
      }
    });

    // Draw once immediately
    lastProgress = st.progress || 0;
    render(lastProgress);

  });
}

// Init Image Sequence on Scroll
document.addEventListener("DOMContentLoaded", () => {
  initImageSequenceScroll();
});

Guide

Implementation

This resource helps you build that Apple-style scroll effect where visuals respond to your scroll in a really tactile way, like you’re “scrubbing” through a video as you move down the page. Daybreak Studio published a great article, of how they make these sequences feel smooth and dependable on real websites, not just in perfect demo conditions. We pulled the key learnings from that article and packaged them into this resource: you export a numbered image sequence, drop the attributes into your HTML, and the script takes care of progressive loading, drawing frames to a canvas with a cover-style look, swapping to a mobile set when available, and falling back for reduced-motion users.

Asset preparation

You can generate your frames with any tool you like as long as the result is a sequentially numbered image set with consistent dimensions and a predictable filename pattern. Common options include Adobe Premiere Pro, After Effects, DaVinci Resolve (free) or basically any video editor or tool that can export an image sequence. In our demo, we used a 10s clip exported at 12fps, which produced 120 frames: Desktop sequence: 1920×1080 at 12fpsMobile sequence: 720×1280 at 12fps Exporting separate desktop and mobile sequences is strongly recommended so mobile users don’t download unnecessary resolution.

File size and format

Finding the balance between smoothness and file size is the difference between a sequence that feels premium and one that feels heavy or laggy, so it’s worth spending a bit of time here before you ship. In our demo, the final export landed at 120 frames total, and we ended up with a desktop folder of 10.7MB and a mobile folder of 6.5MB. That’s a reasonable range for a hero-style sequence, especially since the script progressively loads frames and shows something immediately, rather than blocking the experience until everything is downloaded. We chose WebP for the frame assets because it tends to decode and draw fast in practice, which matters for canvas-based rendering, even if AVIF can sometimes squeeze a slightly smaller total size. If you test AVIF and it feels just as responsive on your target devices, go for it, but if you notice delayed draws or “sticky” frame updates, WebP is a reliable default.

Asset hosting

Use a CDN or file host that gives you a stable, public folder of assets, since the script builds each frame URL by taking a base path and swapping only the frame number in the filename. We recommend Bunny CDN because it’s fast, simple to set up, and makes it easy to keep your frame URLs clean and predictable, but any host works as long as the URLs follow a consistent pattern. The important part is that the only thing changing per frame is the number:

Wrap

Use [data-sequence-wrap] to define the outer section that ScrollTrigger listens to, so the animation progress is driven by scrolling through this block. In our demo, we gave this element a height of 300vh to control the scroll 'duration'.

Scroll Start

Use [data-scroll-start="top top"] (default top top) to control when the sequence begins updating, using the same syntax as GSAP ScrollTrigger start positions. Add this on the wrap.

Scroll End

Use [data-scroll-end="bottom top"] (default bottom top) to control when the sequence stops updating, using the same syntax as GSAP ScrollTrigger end positions. Add this on the wrap.

Element

Use [data-sequence-element] to define the 'stage' that your canvas will size itself to. In our demo, we positioned this inside of a sticky element, so our canvas (see next step) will stick to our scroll position.

Canvas

Use [data-sequence-canvas] to mark the canvas that the script renders into, with the full sequence configuration living directly on this element.

Desktop Source

Use [data-desktop-src] to provide the part of your frame URL that stays the same, so the script can swap only the frame number while keeping everything else identical. To get this value, start from the full URL of your first frame, then remove the numbered part and the extension at the end. For example, if your first frame is: Remove 000.webp and keep the rest, so your desktop source becomes:

Mobile Source

Use [data-mobile-src] (optional but highly recommended) to provide a mobile-specific base URL, falling back to the desktop source when omitted so you can still ship a single sequence.

Filetype

Use [data-filetype="webp"] (default webp) to define the file type you're going to use. We explain our reasoning for WebP at the top of the docs.

Frames

Use [data-frames="120"] to define how many frames exist in the sequence, which determines both how far the animation can progress and what the script treats as the final frame. If you're using a mobile sequence, make sure it has the same amount of frames as your desktop one.‍

Digits

Use [data-digits="3"] (default 3) to define the amount of zero-padding in filenames, so sequences like 000–119 or 0000–0119 work without changing code. ‍

Index Start

Use [data-index-start="0"] (default 0) to define the first frame number used in your filenames, so exports that start at 1 (or any other number) can still map correctly.

Static

Use [data-static-src] to provide a single fallback image that will be shown when the user prefers reduced motion, with the script falling back to the first frame if this isn’t provided.

Common mistakes

Use [data-digits], [data-index-start], and [data-filetype] to exactly match your exported filenames, because a single mismatch here will cause missing frames or a broken setup in general.

URL anatomy

The easiest way to think about it is: the script builds every frame URL from three chunks: a base prefixa padded frame numbera file extension Here’s a concrete example. If your current frame URL is: Then the script is effectively doing this: So it becomes: