Skip to content

Instantly share code, notes, and snippets.

@antiboredom
Created December 15, 2014 16:36
Show Gist options
  • Star 33 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save antiboredom/129fd2311dec0046603e to your computer and use it in GitHub Desktop.
Save antiboredom/129fd2311dec0046603e to your computer and use it in GitHub Desktop.
A simple example showing how to save animated gifs from p5.js sketches, using https://github.com/jnordberg/gif.js
<html>
<head>
<script src="gif.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/p5.js/0.3.11/p5.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/p5.js/0.3.11/addons/p5.dom.js"></script>
<script src="sketch.js"></script>
</head>
<body>
<p>First, allow camera access.<p><p>Then click once to start recording, and another time finish recording and make a gif.</p>
</body>
</html>
var capture;
var recording = false;
var c;
var gif;
function setup() {
c = createCanvas(320, 240);
capture = createCapture(VIDEO);
capture.size(320, 240);
capture.hide();
setupGif();
}
function draw() {
background(255);
image(capture, 0, 0, 320, 240);
if (recording && frameCount % 3 == 0) {
gif.addFrame(c.elt, {delay: 1, copy: true});
}
}
function mousePressed() {
recording = !recording;
if (!recording) {
gif.render();
}
}
function setupGif() {
gif = new GIF({
workers: 2,
quality: 40
});
gif.on('finished', function(blob) {
window.open(URL.createObjectURL(blob));
setupGif();
});
}
@antiboredom
Copy link
Author

To get this working, make sure to download gif.js and gif.worker.js via https://github.com/jnordberg/gif.js.

@Torwegia
Copy link

Thanks for this, just got this working with only a few tweaks. First I had to add the width and the height to the constructor for GIF. Then I could not get the window.open thing to work so I had to make a link to the ObjectURL instead. It means I have to click a link to get the gif to save, but that is fine with me! Thanks again and I hope this helps anyone trying to get this working!

@PC-Four
Copy link

PC-Four commented May 22, 2018

@Torwegia any chance of sharing how you did the link to save the gif?

@sandzu
Copy link

sandzu commented Sep 12, 2018

bump, I'm having an issue where gif.on('finished') never triggers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment