• Stars
    star
    1,052
  • Rank 42,031 (Top 0.9 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 13 years ago
  • Updated 11 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Save a HTML5 Canvas to GIF and Animations. A port of as3gif GIFPlayer to JS

Pure JavaScript HTML5 to (Animated) GIF Conversion

Based on as3gif Ported by Kevin Kwok

This is the raw canvas element saved as a non-animated PNG This is the GIF which was generated from the canvas. This is the GIF which was generated from the canvas.

AS3GIF lets you play and encode animated GIF's with ActionScript 3

Since web pages can usually natively play GIFs fine, it's only a port of the GIFEncoder portions of the library.

Basic Usage

Since it pretty much is GIFEncoder, you could consult the as3gif how-to page

But there are some differences so I'll cover it here anyway.

You first need to include the JS files. It's probably best if you include it in this order, but it shouldn't matter too much.

<script type="text/javascript" src="LZWEncoder.js"></script>
<script type="text/javascript" src="NeuQuant.js"></script>
<script type="text/javascript" src="GIFEncoder.js"></script>

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.

<canvas id="bitmap"></canvas>
<script>
  var canvas = document.getElementById('bitmap');
  var context = canvas.getContext('2d');
  context.fillStyle = 'rgb(255,255,255)';
  context.fillRect(0,0,canvas.width, canvas.height); //GIF can't do transparent so do white
  
  context.fillStyle = "rgb(200,0,0)";  
  context.fillRect (10, 10, 75, 50);   //draw a little red box

Now we need to init the GIFEncoder.

  var encoder = new GIFEncoder();

If you are making an animated gif, you need to add the following

  encoder.setRepeat(0); //0  -> loop forever
                        //1+ -> loop n times then stop
  encoder.setDelay(500); //go to next frame every n milliseconds

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.

  encoder.finish();
  var binary_gif = encoder.stream().getData() //notice this is different from the as3gif package!
  var data_url = 'data:image/gif;base64,'+encode64(binary_gif);

Or download the gif file directly with a given filename as

  encoder.finish();
  encoder.download("download.gif");

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 call setSize which is happily defined just below this one.

Boolean addFrame(ImageData image, true) This adds a frame. This time you just need to pass the ImageData object that you obtained after executing getImageData on the CanvasRenderingContext2D object. And pass true as the second argument and then if the data size and the stored size matches, then it automatically loads the data or it sets the size corresponding to the parameters of the ImageData object, and loads the pixels data.

void download(filename) Download the converted gif file after conversion, with the given file name without any additional function calls or without any additional memory issues when there are large number of frames in the gif file

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 setFrameRate(Number fps) Sets frame rate in frames per second. Equivalent to setDelay(1000/fps). I think that's stupid.

void setQuality(int quality) Sets quality of color quantization (conversion of images to the maximum 256 colors allowed by the GIF specification). Lower values (minimum = 1) produce better colors, but slow processing significantly. 10 is the default, and produces good color mapping at reasonable speeds. Values greater than 20 do not yield significant improvements in speed. BLAH BLAH BLAH. Whatever

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.

I haven't actually tried it yet, but here's some incomplete mock-JS which should be able to do stuff once you add the boring stuff like serializing and deserializing the content (actually, i have most of the serializing done but you have to deserialize that and that's really the boring part).

var frame_index,
    frame_length,
    height, 
    width,
    imageData; //get it from onmessage
    
var encoder = new GIFEncoder(); //create a new GIFEncoder for every new job
if(frame_index == 0){
  encoder.start();
}else{
  encoder.setProperties(true, true); //started, firstFrame
}
encoder.setSize(height, width);
encoder.addFrame(imageData, true);
if(frame_length == frame_index){
  encoder.finish()
}
postMessage(frame_index + encoder.stream().getData()) //on the page, search for the GIF89a to see the frame_index


var animation_parts = new Array(frame_length);
//on the handler side:

var worker = new WebWorker('blahblahblah.js');
worker.onmessage = function(e){
  //handle stuff, like get the frame_index
  animation_parts[frame_index] = frame_data;
  //check when everything else is done and then do animation_parts.join('') and have fun
}
var imdata = context.getImageData(0,0,canvas.width,canvas.height)
var len = canvas.width * canvas.height * 4;
var imarray = [];
for(var i = 0; i < len; i++){
  imarray.push(imdata[i]);
}

worker.postMessage(frame_index + ';' + frame_length + ';' + canvas.height + ';' + canvas.width + ';' + imarray.join(','))

More Repositories

1

ocrad.js

OCR in Javascript via Emscripten
JavaScript
3,451
star
2

whammy

A real time javascript webm encoder based on a canvas hack
JavaScript
992
star
3

player

Almost certainly the first MP3 player of its kind.
JavaScript
276
star
4

cloudsave

Save to the cloud.
JavaScript
168
star
5

eigensheep

massively parallel experimentation with Jupyter and AWS Lambda πŸ‘πŸŒ©πŸ“’
Python
160
star
6

rgb-lab

convert between rgb and L*a*b color spaces in javascript
JavaScript
155
star
7

tesseract-rs

Rust bindings for Tesseract
Rust
113
star
8

weppy

Javascript WebP Library
JavaScript
111
star
9

gocr.js

OCR in Javascript via Emscripten
C
95
star
10

inpaint.js

Telea Inpainting Algorithm in JS
JavaScript
86
star
11

drag2up

Drag a file from your computer to any text field to upload and add link
JavaScript
83
star
12

surplus

Google+ Chrome Extension
JavaScript
68
star
13

summerTorrent

A bit torrent client written in JavaScript, on top of node.js
JavaScript
63
star
14

breadloaf

A draggable, dockable, notebook-style layout engine for React
JavaScript
53
star
15

bzip2.js

a bunzip implementation in pure javascript
JavaScript
37
star
16

obvious-rpc

fully strongly typed client-server communication that is so obvious you'll wonder why it hasn't always been like this
TypeScript
32
star
17

evm

Eulerian Video Magnification in the Browser with JSFeat
JavaScript
31
star
18

js-typed-array-sha1

sha1 with js typed arrays
JavaScript
29
star
19

swipe-gesture

Quick multitouch back/forward gesture for Chromebooks
JavaScript
28
star
20

js-id3v2

A Javascript implementation of ID3v2
JavaScript
28
star
21

autocircle

how to create a magical circle which adds people automagically
Ruby
23
star
22

google-music-protocol

reverse engineered google music protocol
Python
22
star
23

microwave

Mobile-friendly Javascript Data API based Google Wave Client
JavaScript
21
star
24

musicalpha

Upload songs to Google Music Beta on Linux
JavaScript
20
star
25

cloudfall

A simple text editor that syncs to dropbox
JavaScript
20
star
26

js-wikireader

An Offline Wikipedia Dump Reader in Javascript that probably only works on Chrome
JavaScript
19
star
27

jstorrent

A pure JavaScript BitTorrent 1.0 Implementation
JavaScript
17
star
28

heapqueue.js

A simple binary heap priority queue
JavaScript
17
star
29

boa

"its like OAB in python because snake"
Python
15
star
30

distributed-pi

Calculate Pi using distributed computing with JavaScript on Appengine
JavaScript
14
star
31

stick2

a simple stick figure animator with html5
JavaScript
13
star
32

chrome-dropbox

Dropbox + Chrome
JavaScript
13
star
33

hideelements

Chrome Extension. Background Page + Context Menu + Content Script
12
star
34

awesomeness

HTTP based federated protocol for real time hierarchical message manipulation
JavaScript
12
star
35

scratchpad

scratchpad used in khan academy
JavaScript
12
star
36

codemirror-jsx

CodeMirror Mode for React E4X/JSX
JavaScript
11
star
37

3d-sculpt

A simple 3D digital sculpting tool made with JS and HTML5 Canvas
10
star
38

antimatter15

Tiny projects of antimatter15
JavaScript
10
star
39

chromesearch

Desktop Search Engine Chrome Extension
JavaScript
10
star
40

zui

A zooming user interface
JavaScript
9
star
41

antimatter15.github.io

I can't think of a description so I'm describing my inability to think of a description
HTML
9
star
42

js-potrace

A JS port of the C# Vectorize port of the C Potrace
8
star
43

2d-thin-plate-spline

javascript thin plate spline in 2d
JavaScript
8
star
44

derpsacola

use mac accessibility api to scrape screen contents
Swift
8
star
45

chromecorder

Encode screencasts in a cool way copied off of sublimetext.com
CoffeeScript
8
star
46

gmailwave

Integrated Gmail and Wave Chrome Extension
JavaScript
8
star
47

js-ebml

a simple ebml parser in JS for no good reason
JavaScript
7
star
48

gayfish

experimental notebook programming environment
JavaScript
7
star
49

jsvectoreditor

a new version of vectoreditor
JavaScript
7
star
50

wave.js

A Node.JS implementation of the Wave Robot API
6
star
51

k5

differentiable graphics for react
JavaScript
6
star
52

untar.js

untar salvaged from bitjs
JavaScript
6
star
53

readability-iframe

Chrome extension for sites that want to use Readability
JavaScript
5
star
54

creamie

Chrome + Streamie (port of both client and server to Chrome)
JavaScript
5
star
55

pinball

coffeescript pinball game
CoffeeScript
5
star
56

w2_embed

Deep Integration Wave Embed API
JavaScript
5
star
57

autograph

the best most easiest way to graphql
TypeScript
5
star
58

surplus-lite

Google+ notifications in Chrome without colossal memory usage.
JavaScript
5
star
59

omeglebot

A simple Omegle robot that repeats previous conversation phrases semi-intelligently
JavaScript
5
star
60

py-wikireader

A simple offline Wikipedia dump reader
Python
5
star
61

pepper

Use face.com api and canvas to interactively, fancily and automagically add the casually pepper spraying cop to any picture
JavaScript
5
star
62

derp

kinda like version control or something
JavaScript
4
star
63

pdftotext-wasm

poppler pdftotext compiled with emscripten
Dockerfile
4
star
64

facebook-export

Export facebook phone and other data with a screen scraper into CSV format
CoffeeScript
4
star
65

exthub

A self updating, collaborative extension platform
4
star
66

venn-google

Venn Diagrams using Google Suggest
JavaScript
4
star
67

sqlite-vfs-js

TypeScript
4
star
68

espkey

A portable hyperlocal wireless social experiment
C++
4
star
69

x-no-wiretap

Aid the NSA's unwitting collection of domestic internet traffic!
JavaScript
4
star
70

hqx.js

hqx in js
JavaScript
4
star
71

jove

ipython notebook for node.js
JavaScript
4
star
72

franchise-client

database connectors for franchise
JavaScript
4
star
73

speed

Read in a subtitles track and speed up parts of TV shows which don't have talking
4
star
74

wsl

pipe to websocket
JavaScript
4
star
75

fluidizer

Bookmarklet which converts arbitray fixed-width layouts into fluid layouts
JavaScript
4
star
76

d3-pinch-zoom

pinch to zoom for d3 on desktop browsers
JavaScript
4
star
77

vx-comet

A lightweight implementation of the Bayeux protocol
JavaScript
3
star
78

anodize

New Chrome Packaged App BitTorrent Client, mostly just a lot of NodeJS modules stuck together
JavaScript
3
star
79

bitjs

Binary Tools for JavaScript
JavaScript
3
star
80

crossave

Chrome OS File Manager Handler powered by Cloud Save that uploads to a bucketload of services.
JavaScript
3
star
81

evilmeter

chrome extension that detects user agent sniffing
3
star
82

sublime-autobuild

Automatically build on save in Sublime Text 2
Python
3
star
83

fb-grapher

Make purty graphs out of fb data!
JavaScript
3
star
84

dropsync

dropbox syncing for chrome os
3
star
85

rsvgshim

A SVG Shim that renders with RaphaelJS
JavaScript
3
star
86

groebner.js

javascript implementation of buchberger's algorithm for computing a polynomial groebner basis
JavaScript
3
star
87

sprite-codec

A fast screen media optimized codec for embedding in websites
3
star
88

doge

wow. such commit. very push.
Python
3
star
89

identicon-login

A new approach to fighting phishing
PHP
3
star
90

wordless

extract plain text from a word document
JavaScript
3
star
91

kindlespark

Sparknotes -> Kindle via YQL
2
star
92

tensorflow-renderer

first steps toward trying to build a mesh renderer in tensorflow
Jupyter Notebook
2
star
93

retcon

TypeScript
2
star
94

articles

hopefully dis gon b gud
ASP
2
star
95

react-use-nav

a simple routing system for react
2
star
96

timeliner

automatically enable timeline for facebook
2
star
97

facetex

TeX for Facebook Chat
JavaScript
2
star
98

progressive-json

Parse JSON before all of it is loaded
JavaScript
2
star
99

wave-unread-navigator

Show gmail-like arrows listing if unread blips in an open wave are above or below.
JavaScript
2
star
100

keyboard

some failed experiment from a while ago
2
star