Encode Animated GIF in Javascript


Written on Apr 30 2023
megaman run
animation
javascript logo
javascript
nodejs logo
nodejs

Personally, I am fascinated with animation. There are plenty of internet websites and tools for dealing with images, but I wanted to take a closer look at writing the code to do it.

These are the three libraries you will need to have for this to work. Node is our Javascript run-time, canvas adds the html5 canvas to the node eco-system, and finally the gif-encoder-2 will handle the actual encoding of the frames.

1import { Image, createCanvas } from "canvas";
2import GIFEncoder from "gif-encoder-2";
3
4export async function encode(files, width, height) {
5  const encoder = new GIFEncoder(width, height, "octree", true);
6  encoder.setTransparent(true);
7  encoder.start();
8  encoder.setDelay(300);
9  const canvas = createCanvas(width, height);
10  const ctx = canvas.getContext("2d");
11  for (let i = 0; i < files.length; i++) {
12    const img = new Image();
13    img.onload = () => {
14      ctx.drawImage(img, 0, 0);
15      encoder.addFrame(ctx);
16      ctx.clearRect(0, 0, width, height);
17    };
18    img.onerror = (err) => {
19      throw err;
20    };
21    img.src = files[i].filepath;
22  }
23  encoder.finish();
24  return encoder.out.getData();
25}

I used a few of my images lying around to produce this animated gif.

skeleton walking animated gifThe new Animated gif