# gif-writer

**Version 1.6.4 · API 1**

**Tested in:** Firefox 158, ungoogled Chromium 155, WebKitGTK 2.52.6 (cloud); real laptop (16 cores): Firefox 161, Chrome 157 (palette search only, 2026.11.14)

## What it is and how it works

gif-writer makes animated GIFs from canvas pictures, in the browser or Node. One file, 17.2 KB gzipped (12.4 KB minified and gzipped), no dependencies. Optional add-ons apply filters and use Web Workers. It was cut out of Netflow Map's GIF maker.

- One shared palette for the whole animation, so colors do not flicker.
- Only pixels that changed since the last frame are stored, cropped to the changed area.
- Each frame is compressed right away, in WebAssembly when available.

## Why it exists

Most GIFs of apps and games are a still background with a small moving part. Common writers like gifenc and gif.js store every frame in full, so the background is paid for again each frame. On 30 real frames of the Fancy Banana game (cloud Chromium 156, Firefox 158, WebKitGTK 2.52.6, 2026.11.22) the file is 27% to 29% of gifenc's size (208 to 225 KB against 776 to 782 KB) and is written 3.3 to 5.7 times faster.

**Where it helps**

- Short loops for a README, store page or bug report.
- Animated charts and maps.
- Shareable replays made inside an offline page.

**Not for:** photos (256 colors, no dithering), or anywhere a video file works.

## Looks, timing and a worker (since 1.5.0; optional files)

**What.** Four extra files you add only when you want them, each loads on its own page next to `gif-writer.js` and gives a global of its own:
- `gif-writer-fx.js` (`GifWriterFx`): picture filters on RGBA bytes (color grade with brightness, contrast, saturation, warmth, hue and five tones; blur; sharpen; glow; vignette), nine presets, and the timing of an animation: five easing curves, `delaysCs()` (GIF delays are whole hundredths of a second; this rounds so the running total never drifts, and 25 FPS is exactly 4 each), `spinPlan()` (turns, seconds per turn, a pause between turns, reverse, partial swings, names fading in). No DOM: runs in a page, a worker and Node. A 3.8 KB WebAssembly build (SIMD) does blur, sharpen, glow and grade after `GifWriterFx.initWasm()`; the JavaScript stays the fallback and gives the same bytes (125 test cases).
- `gif-writer-worker.js` (`GifWriterWorker`): one message handler (`wasm`, `card`, `init`, `filter`, `palette`, `frame`, `finish`) that is the body of a Web Worker, or is called directly on the page where workers are missing. One worker writes the GIF, all workers can filter.
- `gif-writer-card.js` (`GifWriterCard`): the same filters on the graphics card (WebGL 2) with the same arithmetic. `create()` returns `null` where WebGL 2 is missing and the caller keeps WebAssembly.
- `tolerance` option of `createEncoder` (in `gif-writer.js` itself): `createEncoder(w, h, pal, { tolerance: 8 })` leaves a pixel transparent when it is already shown within that color distance. Smaller files, slightly lossy; uses the JavaScript path, not WebAssembly.

**Why.** Netflow Map makes GIFs of maps that turn around. Filters were the cost, not the GIF coding: in Netflow Map's own measurement (400 item 3D map, 960 pixels wide, one worker, full filter chain), the WebAssembly filters took WebKitGTK from 9.7 to 3.9 s, Firefox from 5.7 to 2.9 s and Chromium from 5.4 to 3.2 s.

```js
GifWriterFx.initWasm().then(function () {
  var f = { contrast: 0.12, saturation: 0.1, sharpen: 0.6 };      // see GifWriterFx.FILTER_PRESETS
  GifWriterFx.apply(rgba, w, h, f);                                // in place; WebAssembly when ready
});
var delays = GifWriterFx.delaysCs([40, 40, 40]);                   // [4, 4, 4]
```

**Test it:** `node modules/gif-writer/test/fx.js` and `node modules/gif-writer/test/fx-wasm.js` (Node), and `tests/gif-writer-fx-browser.js` in the three browsers. Rebuild the filter WebAssembly with `sh wasm/build-fx.sh` then `python3 wasm/embed-fx.py`.

## Try it and test it
**Test it:** `node modules/gif-writer/test/run.js` (an independent GIF decoder reads every file the writer makes and checks every pixel; about 0.2 s). **Try it:** `demo.html`.

## Use
```js
var pics = [ctx.getImageData(0, 0, w, h).data, /* ... one per picture ... */];   // Uint8ClampedArray, RGBA
var pal = GifWriter.makePalette(pics, 255);                 // one palette for the whole animation; give it a few of your pictures, not all
var enc = GifWriter.createEncoder(w, h, pal, { loop: true });
pics.forEach(function (rgba) { enc.add(rgba, 60); });       // how long each picture stays, in milliseconds
var bytes = enc.finish();                                    // Uint8Array: save it as .gif
img.src = URL.createObjectURL(new Blob([bytes], { type: 'image/gif' }));
```
Each picture is compressed the moment you add it, so memory holds the compressed pictures, not the raw ones.

**Advice:** give `makePalette` pictures spread across the whole animation, not just the first few. In the worst case we measured, that made the file 5.5% smaller for 9% more time (container Chromium; the direction is reliable, the exact numbers are not).

## WebAssembly (since 1.2.0)

**What.** The palette search (`makePalette`: color histogram, median cut, k-means) and the picture encoder (`createEncoder`: palette lookup of every pixel, comparison with the last picture, LZW coder) also exist as WebAssembly (9,903 bytes, `wasm/gif.c`), embedded in `gif-writer.js` and used first. They give the same colors and the same GIF bytes as the JavaScript code: 21 encoder scenes and 116 palette sets identical in Node, and 18 of 18 GIFs in every one of 18 browser runs. `GifWriter.wasmAvailable()` says whether the browser allows it; `makePalette(pics, n, { wasm: false })` and `createEncoder(w, h, pal, { wasm: false })` force the JavaScript code.

**Why.** 30 pictures of 640 x 480, median of 3 passes of 5 rounds in rotating order, JavaScript to WebAssembly in ms (lower is better; times faster, higher is better). WebKit's clock moves in whole milliseconds, so quick jobs there are timed 3 to 4 in a row.

Palette search:

| Pictures | ungoogled-chromium 155.0.8059.39-1 | Firefox 158.0 | WebKitGTK 2.52.6 |
|---|---|---|---|
| Photo | 552 to 338 (1.63x) | 580 to 391 (1.48x) | 439 to 351 (1.25x) |
| Flat game picture | 35.4 to 23.4 (1.51x) | 40.0 to 23.0 (1.74x) | 37.0 to 28.8 (1.28x to 1.42x over 5 runs) |
| Small moving block | 27.7 to 19.7 (1.41x) | 28.0 to 20.0 (1.40x) | 21.8 to 20.3 (1.07x) |
| Scrolling bands | 21.3 to 15.1 (1.41x) | 23.0 to 15.0 (1.53x) | 12.2-27.5 to 16.8-17.8 (0.70x to 1.55x over 5 runs) |

Encoding:

| Pictures | ungoogled-chromium 155.0.8059.39-1 | Firefox 158.0 | WebKitGTK 2.52.6 |
|---|---|---|---|
| Photo | 868 to 402 (2.16x) | 901 to 399 (2.26x) | 628 to 390 (1.61x) |
| Flat game picture | 309 to 185 (1.67x) | 376 to 184 (2.04x) | 239 to 167 (1.43x) |
| Small moving block | 43.9 to 29.9 (1.47x) | 38.0 to 25.0 (1.52x) | 31.0 to 28.7 (1.08x) |
| Scrolling bands | 80.4 to 44.3 (1.81x) | 87.0 to 43.0 (2.02x) | 66.0 to 42.3 (1.56x) |

A first small GIF on a fresh page (160 x 120, 4 pictures, start-up included): 44 to 21 ms in Chromium, 34 to 19 in Firefox, 25 to 24 in WebKitGTK.

**Rules.**
- Add `'wasm-unsafe-eval'` to `script-src` if your page has a Content Security Policy. Without it, or if anything goes wrong at the start, the JavaScript code runs and writes the same bytes. A picture area bigger than 4,194,304 pixels also uses the JavaScript code.
- Each encoder has its own WebAssembly memory (about 5 MB plus the pictures); it is freed with the encoder.
- Source `wasm/gif.c`, rebuild `wasm/build.sh`, embed `wasm/embed.py`; both have `--check` to prove the committed files match.

**Thorough palette (1.6.0, off by default).** `makePalette(pics, 255, { thorough: true })` counts every pixel instead of every 3rd or 5th. On 30 noisy frames of 320 x 240 (container Node, wasm on) it made the file 1.1% smaller (725,711 against 733,515 bytes) for about 4 times the palette time (about 316 ms against about 104 ms) when given 8 spread pictures, and 1.6% smaller (721,850) when given all 30 (about 650 ms). Smaller is better, lower time is better. Typical captures with a still background gain nothing worth the time, so leave it off for them.

**Palette sampling (1.4.0).** Above 100,000 pixels in all, `makePalette` counts about every 3rd pixel (every 5th above 1,000,000), at a step with no common factor with the picture's pixel count (so never one that divides its width), and counts every pixel after all when the sample shows fewer than 4,096 distinct colors. WebAssembly and plain JavaScript count the same pixels and give the same palette. A GIF from big photo-like inputs is therefore not byte-identical to one from 1.3.0 (mean picture error within 0.3% on photo-like, gradient and one-pixel-line pictures in the tests); flat, pixel-art and most screenshot pictures give the same bytes as before.

**Honest limits.** In WebKitGTK the palette search on flat pictures is about even with the JavaScript code: scrolling bands came out 0.70x to 1.55x over 5 runs (2026.11.05; the WebAssembly time holds at about 17 ms while the JavaScript time swings from 12 to 27 ms). The cost is copying every picture into WebAssembly memory (it goes in pieces of 16,384 pixels so the copy stays in the processor cache); the JavaScript code counts such pictures in runs at about the same speed. On a real laptop (2026.11.14, 16 cores) the palette search is 1.31x to 1.62x faster in Firefox 161 and 1.11x to 1.67x in Chrome 157, except flat game pictures in Chrome, which are level (0.97x). Everything else in the cloud browsers is 1.07x or faster, and encoding is 1.08x or faster everywhere. The `lzw()` function you can call directly is unchanged JavaScript. Size with terser 5.51.2 (smaller is better): 45,193 bytes as written, 26,530 minified, 12,730 gzipped. Not run: a phone, Safari.

## Compile early (since 1.3.0)

The WebAssembly program starts compiling in the background when the file loads, so the first palette or encoder only starts it. `GifWriter.wasmReady()` gives a promise of `true` or `false` and `GifWriter.wasmModule()` the compiled module (or `null`). Asked for before the compile is done, it compiles on the spot, as before; without WebAssembly nothing changes. The colors and bytes do not change.

Honest numbers: load plus first use, ms, old / new (median of nine fresh pages, right after load; lower is better): Chromium 155 8.3 / 8.7, Firefox 158.0 20 / 20, WebKitGTK 2.52.6 3 / 3 6 / 6. Level within about 1 ms.

## How it compares
On real Fancy Banana frames: files 27% to 29% of gifenc's size and 3.3 to 5.7 times faster in the three test browsers (2026.11.22). Earlier, on generated captures: much smaller files than gifenc when most of the picture stays still, about the same size when everything changes, and bigger as code. Speed (laptop Firefox 160, 16 cores, 2026.10.30, 30 pictures of 320 x 240): a typical capture, a sprite over a still background, is written 6 to 31 times as fast as gifenc and gif.js; when every pixel changes, 1.7 to 3.3 times as fast as gif.js and gifenc with one palette.

| Alternative | Size of the code (smaller is better) | Speed (faster is better) | Features | Where it wins or loses |
|---|---|---|---|---|
| gif-writer 1.6.1 (MIT, this module) | 26,530 bytes minified, 12,730 gzipped (45,193 as written; terser 5.51.2) | Against gifenc and gif.js: see the gifenc and gif.js rows (this module is faster than both on the pictures measured there, laptop Firefox 160) | One palette for the whole animation, only changed pixels stored, GIF89a with loop | Wins on file size for still backgrounds; loses on code size |
| [gifenc](https://github.com/mattdesl/gifenc) (MIT, 1.0.3) | About 5.7 KB gzipped | Laptop Firefox 160: 6 to 11 times slower on a typical capture, 3.3 times slower when every pixel changes (one palette) | Palette quantizing, global or per-picture palettes, writes every pixel of every picture | Wins on code size; loses on file size for mostly still animations |
| [gif.js](https://github.com/jnordberg/gif.js) 0.2.0 (MIT) | 10,430 bytes minified, 3,572 gzipped, plus its worker file, 10,874 bytes minified, 4,057 gzipped (terser 5.51.2 `-c passes=2 -m`) | Laptop Firefox 160, 2 workers: 31 times slower on a typical capture, 1.7 times slower when every pixel changes | NeuQuant color search, optional dithering, encodes in Web Workers; writes every picture in full | Wins on code size and on dithering. Loses on file size for mostly still animations, and needs its worker file served next to the page |
| [omggif](https://github.com/deanm/omggif) 1.0.10 (MIT) | 6,582 bytes minified, 2,554 gzipped | In browsers: not measured | Reads and writes GIFs; you supply the palette and the indexed pixels, no color search | Wins on code size. Loses: no palette search, cropping or transparency handling for you |
| Your own encoder | A few hundred lines | Not measured | Whatever you write | You must test it yourself; the tests here include an independent decoder |

File size, measured (smaller is better): a mostly still animation (30 pictures of 640 x 400, a small ball over a still background) is 23.3 KB here and 159 KB with gifenc (global palette); a worst case with every pixel changing is 1.09 MB here and 1.14 MB with gifenc.

What is different:
- **One palette for the whole animation**, found by median cut and then refined by k-means over the exact colors of the pictures you pass. No flicker from palettes that change between pictures.
- **Only what moved is stored.** A pixel that did not change since the previous picture is written as transparent, and the picture is cropped to the box that did change. A still background costs almost nothing.
- **Plain GIF89a** with a loop block; every viewer reads it.

Where it loses:
- When every pixel changes, the file is only about 5% smaller than gifenc's (smaller is better). Even then it is 3.3 times as fast as gifenc with one palette in laptop Firefox 160 (294 against 960 ms).
- Bigger code than gifenc.
- No dithering and at most 255 colors plus one transparent entry (see Limits).

## Numbers (Node 22, measured 2026-10-17, against gifenc 1.0.3)

> **Node numbers.** The speeds in this section were measured in Node, not in the three test browsers (ungoogled Chromium 155.0.8059.39-1, Firefox 158.0, WebKitGTK 2.52.6), so they are not what a visitor's browser does. Use them to compare rows with each other, not as page speeds. Sizes and counts are exact; only the times depend on the browser. Re-measuring in the three browsers is not done (open item on `TASKS.md`).

| Test | gif-writer | gifenc 1.0.3 |
|---|---|---|
| 30 pictures of 640 x 400, a small ball moving over a still background | 23.3 KB in 101 ms | 159 KB in 152 ms (global palette), 165 KB in 224 ms (palette per picture) |
| Worst case: 20 pictures of 640 x 400 where every pixel changes every time | 1.09 MB in 562 ms | 1.14 MB in 294 ms |

So on a mostly still animation the file is about 6.8 times smaller; when everything changes the file is about 5% smaller but it takes about 1.9 times longer. Your own pictures will land between the two.

## Limits
- At most 255 colors plus one transparent entry (the GIF format allows 256). Photos will look posterized and dithering is not done.
- Making the palette takes time in proportion to the number of different colors in the pictures you pass, not to how many pictures follow: 30 pictures of 640 x 480 with 7 colors take about 30 ms; 30 smooth photo-like pictures with about 513,000 colors take about 0.4 s in Node (smaller is better). Pass a few pictures, not all, to keep it quick.
- The palette is fixed once you create the encoder. If later pictures bring colors the palette never saw, they are matched to the nearest palette color.
- Frame delays are rounded to hundredths of a second and capped at 655,350 ms (the GIF field limit), and browsers commonly show very short delays (10 ms or less) slower than asked.
- All compressed pictures stay in memory until `finish()`.

## Prior art and credits
No code from others; the ideas below are theirs. The code is written for this repository (LFC Foundry, MIT).
- [gifenc](https://github.com/mattdesl/gifenc) (MIT, 1.0.3): compared against, not copied. It is small, fast and well made, with palette quantizing and per-picture or global palettes. It writes every pixel of every picture; this module's saving comes from the transparent-unchanged-pixels step, which is why the first row of the Numbers table differs so much. Its code is smaller gzipped (5.7 KB, against 5.9 KB for 1.0.0 and 7.5 KB for 1.1.0). Use gifenc if you need its API or the speed in the worst case.
- The [GIF89a file format](https://www.w3.org/Graphics/GIF/spec-gif89a.txt) and its LZW compression ([Welch 1984](https://doi.org/10.1109/MC.1984.1659158)) (the format's own method): the published format, implemented from scratch.
- Median cut (the idea of splitting the colors into boxes; [Heckbert 1982](https://doi.org/10.1145/800064.801294)) and k-means ([Lloyd 1982](https://doi.org/10.1109/TIT.1982.1056489)) (moving each palette color to the average of the colors nearest to it): textbook methods, idea only, no code taken.
- Writing your own GIF encoder is a few hundred lines; the tests here include an independent decoder so the bytes can be trusted.

**Original sources** (links checked 2026-11-14; ideas only unless the section above says code is included):

- LZW: Terry Welch, ["A Technique for High-Performance Data Compression"](https://doi.org/10.1109/MC.1984.1659158), 1984; median cut: Paul Heckbert, ["Color image quantization for frame buffer display"](https://doi.org/10.1145/800064.801294), 1982; the [GIF89a specification](https://www.w3.org/Graphics/GIF/spec-gif89a.txt)

## For AI agents
Collect `getImageData(...).data` for each picture, build one palette from every few pictures, add each picture with its delay, call `finish()` once and save the bytes. Keep the canvas size the same for all pictures. Do not pass all pictures of a long animation to `makePalette`; pass about six evenly spaced ones.
