Nono.MA

Export GIFs from p5.js

LAST UPDATED MAY 26, 2022

I've created this p5.js template to quickly make little sketches and export them as GIF animations. (Code below.) Note that, for this to work, you need to have the gif.js and gif.worker.js scripts on the same sketch.1 They are loaded from index.html and sketch.js, respectively. (You can watch this video for a hands-on coding example.)

A circle that scales up and down.
// GIF: Setup
let gif;
let canvas;
let framesToSkip = 3;
let makeGif = false;
let isGifExported = false;

function setupGif() {
    recordedFrames = 0;

    gif = new GIF({
        workers: 2,
        quality: 10,
        workerScript: 'gif.worker.js'
    });

    const uuid = parseInt(Math.random()*10000000);
    gif.on('finished', function(blob) {
        print('GIT: finished')
        rendering = false;
        window.open(URL.createObjectURL(blob));
        saveAs(blob, `bezier-${uuid}@2x.gif`);
        setupGif();
        recordedFrames = 0;
    });
}

function setup() {
  canvas = createCanvas(400, 400);
  setAttributes('antialias', true);
  setupGif();
}

function draw() {
  background(255);
  
  // Drawing code here
  
  // GIF: Add frame
  if (makeGif &&
      !isGifExported &&
      ((frameCount - 1) % framesToSkip == 0 || frameCount == 1)
     ) {
    console.log(`Added frame.`)
    gif.addFrame(canvas.elt, { delay: 30, copy: true });
  }
  
  // GIF: Render when done
  if (makeGif &&
      !isGifExported &&
      // replace with condition to render
      // e.g., frameCount >= 100
      false
     ) {
    print('Exporting GIF...');
    gif.render();
    isGifExported = true;
  }
}

  1. jnordberg/gif.js is a JavaScript GIF encoding library that runs in the browser by Johan Nordberg. 

Blog