gif.js

0.2.0 · abandoned · verified Sun Apr 19

gif.js is a client-side JavaScript library designed for encoding GIFs directly in the browser. It leverages modern browser APIs like Web Workers and Typed Arrays to perform image processing in the background, aiming for fast performance without blocking the main thread. Despite its original aim for efficiency, the project's last stable version is 0.2.0, released over a decade ago (published in 2016, last commit 2017). This indicates it has a virtually non-existent release cadence and is no longer actively maintained. Its key differentiators at the time were its browser-centric approach with Web Worker offloading, which was a significant performance advantage for client-side GIF generation compared to synchronous methods. It accepts image elements, canvas elements, or canvas contexts as frames. However, newer alternatives often offer better performance via WebAssembly and more modern API designs.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize GIF.js, add frames from an image element, a canvas element, and directly from a canvas rendering context. It then renders the GIF and displays it on the page.

<html>
<head>
  <title>GIF.js Quickstart</title>
  <script src="https://cdn.jsdelivr.net/npm/gif.js@0.2.0/dist/gif.js"></script>
</head>
<body>
  <canvas id="myCanvas" width="200" height="200"></canvas>
  <img id="myImage" src="https://via.placeholder.com/200x200.png?text=Frame+1" style="display:none;" alt="Frame 1"/>
  <button id="renderGif">Render GIF</button>

  <script>
    const canvas = document.getElementById('myCanvas');
    const ctx = canvas.getContext('2d');
    const image1 = document.getElementById('myImage');

    const gif = new GIF({
      workers: 2,
      quality: 10,
      width: 200,
      height: 200,
      repeat: 0 // loop forever
    });

    // Add frame from an image element
    gif.addFrame(image1, { delay: 500 });

    // Add frame from a canvas element (draw something first)
    ctx.fillStyle = 'blue';
    ctx.fillRect(50, 50, 100, 100);
    gif.addFrame(canvas, { delay: 500 });

    // Add another frame by clearing and drawing something else
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = 'red';
    ctx.beginPath();
    ctx.arc(100, 100, 50, 0, Math.PI * 2);
    ctx.fill();
    gif.addFrame(ctx, { copy: true, delay: 500 }); // copy: true is important for context

    gif.on('finished', function(blob) {
      const img = document.createElement('img');
      img.src = URL.createObjectURL(blob);
      document.body.appendChild(img);
      console.log('GIF rendered!');
    });

    document.getElementById('renderGif').addEventListener('click', () => {
        console.log('Rendering GIF...');
        gif.render();
    });

  </script>
</body>
</html>

view raw JSON →