GifScratcher

A lightweight, dependency-free JavaScript library that allows you to "scratch" GIFs.

Download GitHub

Demo

Street scene animation

Move your mouse over the image to scratch it.

Documentation

Using a gif

Decoding uses the built-in ImageDecoder API where available (Chrome, Edge, Opera) and falls back to a pure-JS parser (gifuct-js) on Firefox and Safari.

The <img> is a progressive-enhancement fallback: with JavaScript disabled it simply shows the animated gif, and with JS enabled GifScratcher swaps it for a scrubbable canvas. You can also pass the source explicitly with gif: 'animation.gif'.

<div id="target">
  <img src="animation.gif" alt="">
</div>
import { GifScratcher } from './javascripts/gifscratcher.js';

new GifScratcher('#target');

Settings

{
  gif    : string  // Real .gif (optional if target has an <img>)
  auto   : boolean // Autoplay
  scrub  : boolean // Scrub on hover / drag
  cursor : boolean // Add custom cursor
  loader : boolean // Show a spinner while loading
  player : boolean // Show transport controls
  speed  : number  // Playback speed multiplier
}

The canvas is sized from the GIF header before the first frame is decoded, so the loader sits in the correctly-sized box and the page doesn't reflow when the animation appears.

Using a sprite

A standalone sprite-strip version is included in the download as gifscratcher-sprite.js. Instead of decoding a .gif it translates a pre-built horizontal sprite strip on the GPU. Add the first frame as an <img />

<div id="target">
  <img src="animation-first.webp" />
</div>
import { GifScratcherSprite } from './dist/gifscratcher-sprite.js';

new GifScratcherSprite('#target', {
  sprite : 'animation.webp',
  frames : 10
});

Settings

{
  sprite      : string  // Image sprite
  frames      : int     // Number of frames in sprite
  interaction : string  // 'hover' | 'drag'
  auto        : boolean // Autoplay
  cursor      : boolean // Add custom cursor
  speed       : int     // Autoplay speed (rAF ticks per frame)
}

Creating a sprite

To extract every single frame from an animated GIF as individual JPEGs and create a sprite you can use ImageMagick in the terminal.

Install ImageMagick (macOS): brew install imagemagick

To extract the frames run: magick FILENAME.gif -coalesce %02d.webp

To create the sprite run: magick ??.webp +append FILENAME.webp