Capítulo 173 de 411

Chapter 173: Scrub Through a Canvas Image Sequence (Helper)

Core Idea

A helper that ties a tweened "frame" value to drawing the corresponding image from a preloaded sequence onto a <canvas>, typically driven by ScrollTrigger's scrub for a scroll-controlled image-sequence animation.

Key Concepts

  • Config: urls (array of image URLs), canvas (target <canvas> element), optional scrollTrigger config object, optional onUpdate.
  • Preloads all images up front, then tweens a {frame: 0} object; each update draws images[Math.round(playhead.frame)] to the canvas 2D context.
  • Returns a Tween instance, so the caller can further configure or control it.

Code Examples

function imageSequence(config) {
  let playhead = { frame: 0 },
    ctx = gsap.utils.toArray(config.canvas)[0].getContext("2d"),
    images = config.urls.map((url) => { let img = new Image(); img.src = url; return img; }),
    updateImage = () => ctx.drawImage(images[Math.round(playhead.frame)], 0, 0);
  return gsap.to(playhead, {
    frame: images.length - 1, ease: "none", onUpdate: updateImage,
    scrollTrigger: config.scrollTrigger,
  });
}
  • What it demonstrates: driving a canvas-drawn image sequence purely off a numeric tween, decoupled from any DOM/CSS animation.

Key Takeaways

  1. Combine with scrub: true on the ScrollTrigger config for a scroll-linked "video" effect made of still frames.

Connects To

  • ScrollTrigger (scrub): the typical driver for this pattern.