I’ve tried this before but it didn’t work. <canvas> can’t do toDataURL(‘image/gif’), and the primitive GLIF library couldn’t do much so I never had the opportunity to test my gif-merging code that I had. But I’m at it again, this time, porting it from the AS3GIF library, an awesomely comprehensive bitmap to binary gif encoder that even supports LZW compression (and the patent has luckily expired. Yay!). AS3Gif is supposed to “play and encode animated GIFs”, but since web pages can usually natively play GIFs fine, it’s only a port of the GIFEncoder portions of the library. And it works really well. The rest of this post is copied from the Github readme. Interesting how the w2_embed/anonybot embed post was a blog post turned into readme, this is a readme turned into blogpost. I’ll start with a link to the Github repo anyway:

If you want to render the gif through an inline <img> tag or try to save to disk or send to server or anything that requires
conversion into a non-binary string form, you should probably include b64.js too.

<script type="text/javascript" src="b64.js"></script>

Simple enough right? Now to convert stuff to GIF, you need to have a working or at least some imageData-esque array.

Now, you need to tell the magical thing that you’re gonna start inserting frames (even if it’s only one).

encoder.start();

And for the part that took the longest to port: adding a real frame.

encoder.addFrame(context);

In the GIFEncoder version, it accepts a Bitmap. Well, that doesn’t exist in Javascript (natively, anyway) so instead, I use what I feel is a decent analogue: the canvas context. However, if you’re in a situation where you don’t have a real <canvas> element. That’s okay. You can set the second parameter to true and pass a imageData.data-esque array as your first argument. So in other words, you can do encoder.addFrame(fake_imageData, true) as an alternative. However, you must do an encoder.setSize(width, height); before you do any of the addFrames if you pass a imageData.data-like array. If you pass a canvas context, then that’s all okay, because it will automagically do a setSize with the canvas width/height stuff.

Now the last part is to finalize the animation and get it for display.

Docs

Each of the files exposes a single global (see, at least it’s considerate!). But since there’s three files, that means that there’s three globals. But two of them are more of supporting libraries that I don’t totally understand or care about enough to document. So I’m just gonna document GIFEncoder.

new GIFEncoder() This is super parent function. You really don’t need the new keyword because It’s not really even using any special inheritance pattern. It’s a closure that does some var blah = exports.blah = function blah(){ for no good reason. Anyway, it returns an object with a bunch of methods that the section will be devoted to documenting. Note that I’ve never tested more than half of these, so good luck.

Boolean start() This writes the GIF Header and returns false if it fails.

Boolean addFrame(CanvasRenderingContext2D context) This is the magical magic behind everything. This adds a frame.

Boolean addFrame(CanvasPixelArray image, true) This is the magical magic behind everything. This adds a frame. This time you need
you pass true as the second argument and then magic strikes and it loads your canvas pixel array (which can be a real array, I dont care and I think the program has learned from my constant apathy to also not care). But note that if you do, you must first manually callsetSize which is happily defined just below this one.

void setSize(width, height) Sets the canvas size. It’s supposed to be private, but I’m exposing it anyway. Gets called automagically as the size of the first frame if you don’t do that crappy hacky imageData.data hack.

void setDelay(int milliseconds) the number of milliseconds to wait on each frame

void setDispose(int code) Sets the GIF frame disposal code for the last added frame and any subsequent frames. Default is 0 if no transparent color has been set, otherwise 2. I have no clue what this means so I just copypasted
it from the actionscript docs.

void setRepeat(int iter) Sets the number of times the set of GIF frames should be played. Default is 1; 0 means play indefinitely. Must be invoked before the first image is added.

void setTransparent(Number color) Sets the transparent color for the last added frame and any subsequent frames. Since all colors are subject to modification in the quantization process, the color in the final palette for each frame closest to the given color becomes the transparent color for that frame. May be set to null to indicate no transparent color.

ByteArray finish() Adds final trailer to the GIF stream, if you don’t call the finish method the GIF stream will not be valid.

String stream() Yay the only function that returns a non void/boolean. It’s the magical stream function which should have been a getter which JS does support but I didnt’ feel like making it a getter because getters are so weird and inconsistent. Like sure there’s the nice pretty get thing but I think IE9/8 doesn’t implement it because it’s non standard or something and replaced it with a hideously ugly blah blah. So Anyway, it’s a function. It returns a byteArray with three writeByte functions that you wouldn’t care about and a getData() function which returns a binary string with the GIF. There’s also a .bin attribute which contains an array with the binary stuff that I don’t care about.

WebWorkers

The process isn’t really the fastest thing ever, so you should use WebWorkers for piecing together animations more than a few frames long. You can find the rest of the WebWorkers section on the actual readme, because the rest is just a huge block of code with comments.

This works really well, but I’ve come across a problem.
I’m trying to export a two-frame gif, which has 50 colours total; no colours change between the two frames. However, even with setQuality(1), the colours are reduced to 34, and are different on each frame. Adding more setQuality()s, between frames, has no effect on the second frame. I’m working with pixel art, so getting the colours right matters a lot.

hi,
I’ve been researching the options available for client side animated GIFs and I must say that I overlooked this one because of how terribly complicated you made it sound on this page and I was under the impression that this library was not able to control the speed of the frames (both by your animated GIF examples and it not being mentioned anywhere)

as it turns out, I was pleasently surprised that this was one of the easier solutions I tried. I think it might benefit your library if you gave the readme a slight overhaul with an overview of functions so that people may be more inclined to adopt this useful utility. just a thought. thanks.

Wonderful conquer! I have to newbie as you fix your internet site, the best way could possibly my spouse and i sign up to for any blog site site? The particular bank account taught me to be a new appropriate package. I had been a small amount knowledgeable of your your over the air supplied sparkly see-through idea

An easy way to grab frames from canvas animations is to use the JavaScript console built into your browser. There is an article on Stack Overflow titled “grabbing-each-frame-of-an-html5-canvas” that demonstrates how to do this, but the basic principle is that the toDataURL() method allows you to access a single instance of the canvas image and this can then be written back to the browser as an image. To capture a complete sequence, the SetInterval() method can be used.

First of all I would like to say excellent
blog! I had a quick question that I’d like to ask if you do not mind.
I was interested to find out how you center yourself and clear your head
prior to writing. I’ve had difficulty clearing my thoughts in getting my thoughts out.
I do take pleasure in writing but it just seems like the
first 10 to 15 minutes are generally lost just trying to figure
out how to begin. Any ideas or hints? Thanks!

I’m truly enjoying the design and layout of your site. It’s a very easy on the eyes which makes it much
more pleasant for me to come here and visit more often.
Did you hire out a developer to create your theme?
Exceptional work!

About

I’m really not that interesting. This blog is just a place where I talk about random ideas or projects like just about everyone else. I’ve never really been into talking about myself, rather just the stuff I do or think. I may be somewhat paranoid, or whatever. I think I’m an INTP but I’m not […]more →