Guide · Build

Canvas image sequence scroll animation in Next.js

By Md Mahafuj Alam · Updated

A canvas image sequence scroll animation pins a full-screen canvas while a tall section scrolls past, maps scroll progress to a frame index and draws that frame with drawImage. In Next.js App Router it lives in one client component backed by a small framework-free player that preloads frames coarse to fine, draws the nearest loaded frame once per animation frame and cleans up on unmount. This guide builds both a native sticky version and a GSAP ScrollTrigger version, with full working code.

How the scroll scrub works

The effect has four moving parts. A section several screens tall gives the page scroll distance. Inside it, a wrapper sticks to the top of the viewport, so the canvas stays put while that distance is consumed. A scroll handler turns the section's position into a progress value from 0 to 1. Progress times the last frame index gives the frame to draw.

The frames are still images exported from a video. Drawing them on a canvas, rather than swapping an <img> source, avoids layout work and flicker on every change: drawImage only paints pixels. Scrubbing a <video> element by setting currentTime looks simpler, but seeking is tied to keyframes and decoder latency, so it stutters when the scroll changes direction. The trade-offs are covered in image sequence vs video vs three.js.

The code below splits the work in two. A plain TypeScript player handles loading, sizing and drawing. A thin React component owns the DOM and decides which frame the scroll asks for. That split keeps React renders out of the hot path and makes it easy to swap the scroll source for GSAP later. If you are planning the whole site rather than one section, start with the guide to building a 3D website with Claude.

Prepare the frames

Export the clip as numbered WebP files in public/frames/desktop and public/frames/mobile, named frame_0001.webp, frame_0002.webp and so on. The component builds URLs from that pattern, so change the frameUrl helper if your export uses another one. You can extract frames in the browser with the free video to frames tool, or script it with FFmpeg.

  • Two sets, same count. A landscape set for desktop and a 9:16 portrait set for phones. Cropping a landscape frame to a phone screen throws away most of the picture.
  • Frame count drives scroll feel. More frames give smoother motion over a long scroll, but every frame is a request and a decode.
  • Total weight matters more than frame size. The visitor downloads the whole set while they scroll.
Frame budgets from two live Edok Studio Motion templates
TemplateFramesFrame weightMobile frames
Orbitly69116.59 MBDedicated portrait set
Kestra44326 MBSeparate 9:16 set

Kestra ships two frame tiers: light previews load first, then 1920 × 1072 HD frames stream in, and HD frames far from the scroll position are released from memory. The player below implements the simpler single-tier version of that idea.

Load and draw frames outside React

The player takes a canvas and a list of URLs and returns two functions: show(frame) and destroy(). It has no React imports, so it never triggers a render and you can reuse it with any scroll library.

lib/sequence-player.tsts
export type SequencePlayer = {
  /** Ask for a frame. Draws it, or the nearest frame that has loaded. */
  show: (frame: number) => void;
  /** Stop loading, cancel pending draws, release the images. */
  destroy: () => void;
};

type Options = {
  /** Frame to show first (and the only frame loaded with preload: 'one'). */
  first?: number;
  /** 'all' streams every frame; 'one' loads just `first` (reduced motion). */
  preload?: 'all' | 'one';
  /** Parallel downloads. */
  concurrency?: number;
};

/** Coarse to fine: every 16th frame, then every 8th, 4th, 2nd, then the rest. */
function loadOrder(count: number, first: number): number[] {
  const seen = new Uint8Array(count);
  const order = [first];
  seen[first] = 1;
  for (let step = 16; step >= 1; step /= 2) {
    for (let i = 0; i < count; i += step) {
      if (!seen[i]) {
        seen[i] = 1;
        order.push(i);
      }
    }
  }
  return order;
}

export function createSequencePlayer(
  canvas: HTMLCanvasElement,
  urls: string[],
  { first = 0, preload = 'all', concurrency = 6 }: Options = {},
): SequencePlayer {
  const ctx = canvas.getContext('2d');
  const count = urls.length;
  const frames: (HTMLImageElement | null)[] = new Array(count).fill(null);
  const pending = new Set<HTMLImageElement>();
  let wanted = first; // frame the scroll position asks for
  let drawn = -1; // frame currently on the canvas
  let raf = 0;
  let destroyed = false;

  // Cover-fit: scale until both sides fill the canvas, centre, crop the rest.
  const draw = (img: HTMLImageElement) => {
    if (!ctx) return;
    const cw = canvas.width;
    const ch = canvas.height;
    const scale = Math.max(cw / img.naturalWidth, ch / img.naturalHeight);
    const w = img.naturalWidth * scale;
    const h = img.naturalHeight * scale;
    ctx.drawImage(img, (cw - w) / 2, (ch - h) / 2, w, h);
  };

  const nearestLoaded = (i: number) => {
    for (let d = 0; d < count; d++) {
      if (frames[i - d]) return i - d;
      if (frames[i + d]) return i + d;
    }
    return -1;
  };

  const render = () => {
    raf = 0;
    const index = nearestLoaded(wanted);
    if (index === -1 || index === drawn) return;
    draw(frames[index]!);
    drawn = index;
  };

  // Many scroll events, one draw per display frame.
  const requestRender = () => {
    if (!raf && !destroyed) raf = requestAnimationFrame(render);
  };

  // Size the backing store to the CSS size x devicePixelRatio (capped at 2).
  const resize = () => {
    const dpr = Math.min(window.devicePixelRatio || 1, 2);
    const { width, height } = canvas.getBoundingClientRect();
    canvas.width = Math.round(width * dpr);
    canvas.height = Math.round(height * dpr);
    drawn = -1; // changing width/height clears the canvas
    requestRender();
  };
  const observer = new ResizeObserver(resize);
  observer.observe(canvas);

  const load = async (i: number) => {
    const img = new Image();
    pending.add(img);
    img.src = urls[i];
    try {
      await img.decode(); // resolves once the image is ready to draw
    } catch {
      return; // a missing frame is covered by its nearest neighbour
    } finally {
      pending.delete(img);
    }
    if (destroyed) return;
    frames[i] = img;
    requestRender();
  };

  const queue = preload === 'one' ? [first] : loadOrder(count, first);
  const worker = async () => {
    while (!destroyed && queue.length > 0) await load(queue.shift()!);
  };
  for (let k = 0; k < concurrency; k++) void worker();

  return {
    show(frame) {
      wanted = Math.min(Math.max(Math.round(frame), 0), count - 1);
      requestRender();
    },
    destroy() {
      destroyed = true;
      cancelAnimationFrame(raf);
      observer.disconnect();
      pending.forEach((img) => img.removeAttribute('src')); // drop in-flight requests
      frames.fill(null);
    },
  };
}

Why HTMLImageElement and not createImageBitmap

createImageBitmap decodes an image into a bitmap that draws fast and can decode off the main thread when you pass it a Blob. The catch is memory. A decoded 1920 × 1080 frame is 1920 × 1080 × 4 bytes, about 8.3 MB, and an ImageBitmap holds those pixels until you call close(). Hundreds of them will exhaust a phone. An HTMLImageElement keeps the compressed file and lets the browser manage decoded copies, so it is the safer default for a full sequence. Reach for createImageBitmap when you keep only a window of frames around the scroll position and close the rest.

Progressive loading and the nearest loaded frame

Loading frames in order means a fast scroller hits a blank canvas. loadOrder fetches every 16th frame first, then fills the gaps at every 8th, 4th, 2nd and finally every frame. Within a second or two the whole scroll range has coarse coverage, and the animation sharpens as the rest arrive. nearestLoaded searches outwards from the requested index, so the canvas always shows the closest frame available instead of nothing. When a closer frame finishes loading, load calls requestRender and the canvas updates.

One draw per display frame

Scroll events can fire more often than the screen refreshes. requestRender schedules at most one requestAnimationFrame callback, and render skips the draw when the frame on screen is already the right one. img.decode() resolves only when the image is ready to paint, which keeps decode work out of the draw call.

Cover-fit drawing and devicePixelRatio

The canvas fills the viewport, but the viewport rarely matches the frame's aspect ratio. The draw function reproduces CSS object-fit: cover: take the larger of the two scale ratios so both sides fill the canvas, then centre the result. The overflow on one axis falls outside the canvas and is cropped.

Cover-fit, step by stepts
// Canvas 1000 x 1000, frame 1920 x 1080:
// scale = max(1000 / 1920, 1000 / 1080) = max(0.52, 0.926) = 0.926
// drawn size = 1778 x 1000, x offset = (1000 - 1778) / 2 = -389
export function coverRect(cw: number, ch: number, iw: number, ih: number) {
  const scale = Math.max(cw / iw, ch / ih);
  const w = iw * scale;
  const h = ih * scale;
  return { x: (cw - w) / 2, y: (ch - h) / 2, w, h };
}

A canvas has two sizes. CSS sets how big it looks; the width and height attributes set how many pixels it holds. If they match on a display with a devicePixelRatio of 2 or 3, the browser upscales the bitmap and every frame looks soft. resize reads the CSS size with getBoundingClientRect and multiplies by the ratio.

  • Cap the ratio at 2. A 3x phone would otherwise need a backing store over twice the pixels of a 2x one, and the frames are rarely sharp enough for the difference to show.
  • Redraw after every resize. Assigning width or height clears the canvas, so resize resets drawn and requests a render.
  • Use a ResizeObserver. It fires once on observe, so the first size is set without extra code, and it catches layout changes that a window resize listener misses.

The sticky canvas component

The component renders a section scrollVh viewport heights tall, with a sticky wrapper that holds the canvas. It needs 'use client' because it touches window and the DOM, and all of that happens inside useEffect, which never runs on the server.

components/ScrollSequence.tsxtsx
'use client';

import { useEffect, useRef } from 'react';
import { createSequencePlayer } from '@/lib/sequence-player';

type Props = {
  /** Frames per set; both sets must have the same count. */
  frameCount: number;
  /** Landscape frames, e.g. "/frames/desktop". */
  desktopDir: string;
  /** 9:16 frames for portrait screens, e.g. "/frames/mobile". */
  mobileDir: string;
  /** Scroll length of the scrub, in viewport heights. */
  scrollVh?: number;
  /** Frame shown first, and the only one shown with reduced motion. */
  posterFrame?: number;
};

const frameUrl = (dir: string, i: number) =>
  `${dir}/frame_${String(i + 1).padStart(4, '0')}.webp`;

export default function ScrollSequence({
  frameCount,
  desktopDir,
  mobileDir,
  scrollVh = 400,
  posterFrame = 0,
}: Props) {
  const sectionRef = useRef<HTMLElement>(null);
  const canvasRef = useRef<HTMLCanvasElement>(null);

  useEffect(() => {
    const section = sectionRef.current;
    const canvas = canvasRef.current;
    if (!section || !canvas) return;

    const portrait = window.matchMedia('(orientation: portrait)').matches;
    const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    const dir = portrait ? mobileDir : desktopDir;
    const urls = Array.from({ length: frameCount }, (_, i) => frameUrl(dir, i));

    const player = createSequencePlayer(canvas, urls, {
      first: posterFrame,
      preload: reduced ? 'one' : 'all',
    });
    if (reduced) return () => player.destroy();

    // Progress = how far the section has scrolled past the top of the viewport.
    const onScroll = () => {
      const rect = section.getBoundingClientRect();
      const distance = rect.height - window.innerHeight;
      const progress = distance > 0 ? Math.min(Math.max(-rect.top / distance, 0), 1) : 0;
      player.show(progress * (frameCount - 1));
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();

    return () => {
      window.removeEventListener('scroll', onScroll);
      player.destroy();
    };
  }, [frameCount, desktopDir, mobileDir, posterFrame]);

  return (
    <section
      ref={sectionRef}
      className="scroll-sequence"
      style={{ position: 'relative', height: `${scrollVh}vh` }}
    >
      <div style={{ position: 'sticky', top: 0, height: '100svh', overflow: 'hidden' }}>
        <canvas
          ref={canvasRef}
          aria-hidden="true"
          style={{ display: 'block', width: '100%', height: '100%' }}
        />
      </div>
    </section>
  );
}

Progress is the distance the section has moved above the viewport top, divided by the distance it can move while the sticky wrapper is pinned: its height minus one viewport. Clamping keeps the value at 0 before the section arrives and at 1 after it leaves. The page itself can stay a Server Component:

app/page.tsxtsx
import ScrollSequence from '@/components/ScrollSequence';

export default function Home() {
  return (
    <main>
      <ScrollSequence
        frameCount={240}
        desktopDir="/frames/desktop"
        mobileDir="/frames/mobile"
        scrollVh={400}
      />
      <section style={{ minHeight: '100vh' }}>The story continues here.</section>
    </main>
  );
}

The GSAP ScrollTrigger version

Native sticky is enough for one sequence. Switch to GSAP ScrollTrigger when the sequence shares a timeline with text, overlays or a three.js layer, or when you want smoothing between scroll input and the playhead. The player stays the same; only the scroll source changes.

components/ScrollSequenceGsap.tsxtsx
'use client';

import { useRef } from 'react';
import { gsap } from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
import { useGSAP } from '@gsap/react';
import { createSequencePlayer } from '@/lib/sequence-player';

gsap.registerPlugin(ScrollTrigger, useGSAP);

type Props = {
  urls: string[];
  /** Scroll distance of the scrub, in viewport heights. */
  scrollScreens?: number;
};

export default function ScrollSequenceGsap({ urls, scrollScreens = 3 }: Props) {
  const sectionRef = useRef<HTMLElement>(null);
  const canvasRef = useRef<HTMLCanvasElement>(null);

  useGSAP(
    () => {
      const canvas = canvasRef.current;
      if (!canvas) return;
      const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
      const player = createSequencePlayer(canvas, urls, { preload: reduced ? 'one' : 'all' });
      const mm = gsap.matchMedia();

      mm.add('(prefers-reduced-motion: no-preference)', () => {
        const playhead = { frame: 0 };
        gsap.to(playhead, {
          frame: urls.length - 1,
          ease: 'none',
          onUpdate: () => player.show(playhead.frame),
          scrollTrigger: {
            trigger: sectionRef.current,
            start: 'top top',
            end: () => `+=${window.innerHeight * scrollScreens}`,
            pin: true,
            scrub: 0.5,
            invalidateOnRefresh: true,
          },
        });
      });

      return () => {
        mm.revert();
        player.destroy();
      };
    },
    { scope: sectionRef, dependencies: [urls, scrollScreens] },
  );

  return (
    <section ref={sectionRef} style={{ height: '100svh', overflow: 'hidden' }}>
      <canvas
        ref={canvasRef}
        aria-hidden="true"
        style={{ display: 'block', width: '100%', height: '100%' }}
      />
    </section>
  );
}
  • A tween drives a plain object. GSAP animates playhead.frame from 0 to the last index, and onUpdate passes it to the player, which rounds it.
  • scrub: 0.5 makes the playhead take half a second to catch up with the scrollbar, which smooths out coarse wheel steps. Use scrub: true for a hard link.
  • pin: true replaces the sticky wrapper. ScrollTrigger adds pin spacing so the next section waits until the scrub ends.
  • A function for end. end depends on the viewport height, so it is a function, and invalidateOnRefresh recomputes it when ScrollTrigger refreshes after a resize.
  • Cleanup in one place. useGSAP reverts everything created inside it on unmount; the returned function also reverts the matchMedia handlers and destroys the player.

Pass a stable urls array, for example built in a Server Component or with useMemo. A new array on every render changes the dependency and rebuilds the player. Adding Lenis smooth scrolling on top needs one extra sync step, covered in GSAP ScrollTrigger + Lenis in Next.js. The Orbitly template is built on the same stack: a 691-frame image sequence scrubbed on a canvas with Next.js, TypeScript, GSAP ScrollTrigger and Lenis.

Mobile frames and reduced motion

The component picks the frame set once, on mount, with matchMedia('(orientation: portrait)'). A portrait phone gets 9:16 frames composed for a tall screen; everything else gets landscape. Re-picking on every rotation would throw away loaded frames, so treat orientation as a mount-time choice. If you need to react to rotation, put a key on the component that changes with orientation and let React remount it.

Mobile is also where memory runs out first. Portrait frames at phone resolution are smaller than desktop frames, which lowers both download and decoded size. Keep the portrait set at the resolution the screen can show, not the source video's.

Reduced motion

Visitors who set prefers-reduced-motion: reduce should not get a full-screen animation tied to scrolling. Both components load a single poster frame in that case and skip the scroll handler. Collapse the tall section so they do not scroll through four screens of a still image:

app/globals.csscss
@media (prefers-reduced-motion: reduce) {
  .scroll-sequence {
    height: 100svh !important;
  }
}

The !important rule beats the inline height. In the GSAP version, gsap.matchMedia never creates the pin for these visitors, so the section is already one screen tall.

Cleanup on unmount and common bugs

In development, React Strict Mode mounts, unmounts and remounts each component to surface missing cleanup. The effect above survives that because destroy cancels the pending animation frame, disconnects the ResizeObserver, stops the download workers, removes the src of in-flight images and releases loaded ones. The destroyed flag stops any decode that resolves late from writing into a dead player.

SymptomCauseFix
Blurry frames on phones and Retina screensCanvas pixel size equals its CSS sizeMultiply by devicePixelRatio in resize
Frames stretched or squasheddrawImage to the full canvas sizeUse the cover-fit math
Canvas flashes blank on resizeSetting width or height clears the canvasReset drawn and redraw
Blank canvas on fast scrollFrames load in orderCoarse-to-fine order plus nearest loaded frame
Double downloads in developmentStrict Mode remount without cleanupReturn destroy from the effect
Animation ends before the section doesProgress divided by full section heightDivide by height minus one viewport

Once the component works, the remaining work is performance on real phones and reduced-motion polish. When you would rather start from a finished build, the template catalogue has complete scroll stories with frames, copy and code included. For the APIs used here, see MDN on drawImage and createImageBitmap, and the ScrollTrigger documentation.

FAQ

Questions, answered.

The questions people ask most about this topic.

01How many frames does a canvas scroll animation need?

Enough that each frame covers a small slice of scroll. A few hundred frames over three to five screens of scroll is common; the live Orbitly template uses 691 and Kestra uses 443. More frames mean smoother motion but more downloads, so balance count against total weight.

02Should I use a canvas or a video element for scroll scrubbing?

Use a canvas with an image sequence when the animation must follow the scrollbar exactly in both directions. Video seeking depends on keyframes and decoder latency, so it tends to stutter when scrubbed. Video is fine for clips that simply play.

03Why does my canvas look blurry on an iPhone?

The canvas backing store is the same size as its CSS box, so the browser upscales it on a high-density screen. Set canvas.width and canvas.height to the CSS size multiplied by devicePixelRatio, capped at 2, and redraw after every resize.

04Do I need GSAP for an image sequence scroll animation?

No. A sticky wrapper and a scroll listener are enough for a single sequence. GSAP ScrollTrigger helps when the sequence shares a timeline with other animations, when you want scrub smoothing, or when you add Lenis smooth scrolling.

05Does this work with the Next.js App Router?

Yes. Put the component in a file marked use client and keep all window and DOM access inside useEffect or useGSAP. The page that renders it can stay a Server Component and pass plain props such as the frame folder and count.