├── .gitignore
├── LICENSE
├── README.markdown
├── example.html
├── example_gifs
├── rub_test.gif
└── rub_test_preview.jpg
├── libgif.js
├── package.json
└── rubbable.js
/.gitignore:
--------------------------------------------------------------------------------
1 | .*.swp
2 | .DS_Store
3 |
4 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright (c) 2011 Shachaf Ben-Kiki
2 |
3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4 |
5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6 |
7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
8 |
--------------------------------------------------------------------------------
/README.markdown:
--------------------------------------------------------------------------------
1 | Forked from Buzzfeed's [libgif-js](https://github.com/buzzfeed/libgif-js) and make it hostable as an npm module.
2 |
3 | # Overview
4 |
5 | Forked from the excelent jsgif project (https://github.com/shachaf/jsgif), which was implemented as a bookmarklet to manipulate animated gifs (http://slbkbs.org/jsgif).
6 |
7 | This is an attempt to pull out the gif parsing and playing logic, seperate it from the bookmarklet, and publish it as a library that you can use in your project.
8 |
9 | As an added bonus, you can make gifs "rubbable" so that scrubbing with your mouse (or rubbing with your finger on a touch device) cause the gif to move back and forth.
10 |
11 | # Example
12 |
13 | Please see example.html for, you know, an example. This will demonstrate how to use basic play controls for a gif, and also a rubbable one.
14 |
15 | Please note: this example must be loaded via a webserver, not directly from disk. I.e. http://localhost/libgif-js/example.html NOT file:///libgif-js/example.html. See the same-domain origin caveat at the bottom of this document for more information.
16 |
17 | For a hosted example, check out this post on BuzzFeed.com (http://www.buzzfeed.com/yacomink/rubbable-gifs)
18 |
19 | # Technical Details
20 |
21 | Of note to the developer, libjs.gif contains a class SuperGif, which can be used to manipulate animated gifs.
22 |
23 | ## Class: SuperGif
24 |
25 | ### Example usage:
26 |
27 | ```html
28 |
30 |
31 |
41 | ```
42 |
43 | ### Image tag attributes:
44 |
45 | * **rel:animated_src** - If this url is specified, it's loaded into the player instead of src.
46 | This allows a preview frame to be shown until animated gif data is streamed into the canvas
47 |
48 | * **rel:auto_play** - Defaults to 1 if not specified. If set to zero, a call to the play() method is needed
49 |
50 | * **rel:rubbable** - Defaults to 0 if not specified. If set to 1, the gif will be a canvas with handlers to handle rubbing.
51 |
52 | ### Constructor options
53 |
54 | * **gif** - Required. The DOM element of an img tag.
55 | * **loop_mode** - Optional. Setting this to false will force disable looping of the gif.
56 | * **auto\_play** - Optional. Same as the rel:auto_play attribute above, this arg overrides the img tag info.
57 | * **max\_width** - Optional. Scale images over max\_width down to max_width. Helpful with mobile.
58 | * **rubbable** - Optional. Make it rubbable.
59 | * **on_end** - Optional. Add a callback for when the gif reaches the end of a single loop (one iteration). The first argument passed will be the gif HTMLElement.
60 | * **loop_delay** - Optional. The amount of time to pause (in ms) after each single loop (iteration).
61 | * **progressbar_height** - Optional. The height of the progress bar.
62 | * **progressbar_background_color** - Optional. The background color of the progress bar.
63 | * **progressbar_foreground_color** - Optional. The foreground color of the progress bar.
64 |
65 | ### Instance methods
66 |
67 | #### loading
68 | * **load( callback )** - Loads the gif specified by the src or rel:animated_src sttributie of the img tag into a canvas element and then calls callback if one is passed
69 | * **load_url( src, callback )** - Loads the gif file specified in the src argument into a canvas element and then calls callback if one is passed
70 |
71 | #### play controls
72 | * **play** - Start playing the gif
73 | * **pause** - Stop playing the gif
74 | * **move_to(i)** - Move to frame i of the gif
75 | * **move_relative(i)** - Move i frames ahead (or behind if i < 0)
76 |
77 | #### getters
78 | * **get_canvas** - The canvas element that the gif is playing in. Handy for assigning event handlers to.
79 | * **get_playing** - Whether or not the gif is currently playing
80 | * **get_loading** - Whether or not the gif has finished loading/parsing
81 | * **get\_auto_play** - Whether or not the gif is set to play automatically
82 | * **get_length** - The number of frames in the gif
83 | * **get\_current_frame** - The index of the currently displayed frame of the gif
84 |
85 | ## Caveat: same-domain origin
86 |
87 | The gif has to be on the same domain (and port and protocol) as the page you're loading.
88 |
89 | The library works by parsing gif image data in js, extracting individual frames, and rendering them on a canvas element. There is no way to get the raw image data from a normal image load, so this library does an XHR request for the image and forces the MIME-type to "text/plain". Consequently, using this library is subject to all the same cross-domain restrictions as any other XHR request.
90 |
--------------------------------------------------------------------------------
/example.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 | Example gif
11 |
12 |
13 |
14 |
15 |
16 | Example with controls and no auto-play
17 |
18 |
19 |
23 | Pause |
24 | Play |
25 | Restart |
26 | Step forward |
27 | Step back
28 |
29 | Example with rubbing and auto-play on
30 |
31 |
32 |
36 |
37 |
38 | Image via mlkshk
39 |
40 |
41 |
42 |
43 |
--------------------------------------------------------------------------------
/example_gifs/rub_test.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kelyvin/libgif-js/2a9ce40d11a58ec184cc1545760f0acd956b86a1/example_gifs/rub_test.gif
--------------------------------------------------------------------------------
/example_gifs/rub_test_preview.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kelyvin/libgif-js/2a9ce40d11a58ec184cc1545760f0acd956b86a1/example_gifs/rub_test_preview.jpg
--------------------------------------------------------------------------------
/libgif.js:
--------------------------------------------------------------------------------
1 | /*
2 | SuperGif
3 |
4 | Example usage:
5 |
6 |
7 |
8 |
16 |
17 | Image tag attributes:
18 |
19 | rel:animated_src - If this url is specified, it's loaded into the player instead of src.
20 | This allows a preview frame to be shown until animated gif data is streamed into the canvas
21 |
22 | rel:auto_play - Defaults to 1 if not specified. If set to zero, a call to the play() method is needed
23 |
24 | Constructor options args
25 |
26 | gif Required. The DOM element of an img tag.
27 | loop_mode Optional. Setting this to false will force disable looping of the gif.
28 | auto_play Optional. Same as the rel:auto_play attribute above, this arg overrides the img tag info.
29 | max_width Optional. Scale images over max_width down to max_width. Helpful with mobile.
30 | on_end Optional. Add a callback for when the gif reaches the end of a single loop (one iteration). The first argument passed will be the gif HTMLElement.
31 | loop_delay Optional. The amount of time to pause (in ms) after each single loop (iteration).
32 | draw_while_loading Optional. Determines whether the gif will be drawn to the canvas whilst it is loaded.
33 | show_progress_bar Optional. Only applies when draw_while_loading is set to true.
34 |
35 | Instance methods
36 |
37 | // loading
38 | load( callback ) Loads the gif specified by the src or rel:animated_src sttributie of the img tag into a canvas element and then calls callback if one is passed
39 | load_url( src, callback ) Loads the gif file specified in the src argument into a canvas element and then calls callback if one is passed
40 |
41 | // play controls
42 | play - Start playing the gif
43 | pause - Stop playing the gif
44 | move_to(i) - Move to frame i of the gif
45 | move_relative(i) - Move i frames ahead (or behind if i < 0)
46 |
47 | // getters
48 | get_canvas The canvas element that the gif is playing in. Handy for assigning event handlers to.
49 | get_playing Whether or not the gif is currently playing
50 | get_loading Whether or not the gif has finished loading/parsing
51 | get_auto_play Whether or not the gif is set to play automatically
52 | get_length The number of frames in the gif
53 | get_current_frame The index of the currently displayed frame of the gif
54 | get_frames An array containing the data for all parsed frames
55 | get_duration Returns the duration of the gif in hundredths of a second (standard for GIF spec)
56 | get_duration_ms Returns the duration of the gif in milliseconds
57 |
58 | For additional customization (viewport inside iframe) these params may be passed:
59 | c_w, c_h - width and height of canvas
60 | vp_t, vp_l, vp_ w, vp_h - top, left, width and height of the viewport
61 |
62 | A bonus: few articles to understand what is going on
63 | http://enthusiasms.org/post/16976438906
64 | http://www.matthewflickinger.com/lab/whatsinagif/bits_and_bytes.asp
65 | http://humpy77.deviantart.com/journal/Frame-Delay-Times-for-Animated-GIFs-214150546
66 |
67 | */
68 | (function (root, factory) {
69 | if (typeof define === 'function' && define.amd) {
70 | define([], factory);
71 | } else if (typeof exports === 'object') {
72 | module.exports = factory();
73 | } else {
74 | root.SuperGif = factory();
75 | }
76 | }(this, function () {
77 | // Generic functions
78 | var bitsToNum = function (ba) {
79 | return ba.reduce(function (s, n) {
80 | return s * 2 + n;
81 | }, 0);
82 | };
83 |
84 | var byteToBitArr = function (bite) {
85 | var a = [];
86 | for (var i = 7; i >= 0; i--) {
87 | a.push( !! (bite & (1 << i)));
88 | }
89 | return a;
90 | };
91 |
92 | // Stream
93 | /**
94 | * @constructor
95 | */
96 | // Make compiler happy.
97 | var Stream = function (data) {
98 | this.data = data;
99 | this.len = this.data.length;
100 | this.pos = 0;
101 |
102 | this.readByte = function () {
103 | if (this.pos >= this.data.length) {
104 | throw new Error('Attempted to read past end of stream.');
105 | }
106 | if (data instanceof Uint8Array)
107 | return data[this.pos++];
108 | else
109 | return data.charCodeAt(this.pos++) & 0xFF;
110 | };
111 |
112 | this.readBytes = function (n) {
113 | var bytes = [];
114 | for (var i = 0; i < n; i++) {
115 | bytes.push(this.readByte());
116 | }
117 | return bytes;
118 | };
119 |
120 | this.read = function (n) {
121 | var s = '';
122 | for (var i = 0; i < n; i++) {
123 | s += String.fromCharCode(this.readByte());
124 | }
125 | return s;
126 | };
127 |
128 | this.readUnsigned = function () { // Little-endian.
129 | var a = this.readBytes(2);
130 | return (a[1] << 8) + a[0];
131 | };
132 | };
133 |
134 | var lzwDecode = function (minCodeSize, data) {
135 | // TODO: Now that the GIF parser is a bit different, maybe this should get an array of bytes instead of a String?
136 | var pos = 0; // Maybe this streaming thing should be merged with the Stream?
137 | var readCode = function (size) {
138 | var code = 0;
139 | for (var i = 0; i < size; i++) {
140 | if (data.charCodeAt(pos >> 3) & (1 << (pos & 7))) {
141 | code |= 1 << i;
142 | }
143 | pos++;
144 | }
145 | return code;
146 | };
147 |
148 | var output = [];
149 |
150 | var clearCode = 1 << minCodeSize;
151 | var eoiCode = clearCode + 1;
152 |
153 | var codeSize = minCodeSize + 1;
154 |
155 | var dict = [];
156 |
157 | var clear = function () {
158 | dict = [];
159 | codeSize = minCodeSize + 1;
160 | for (var i = 0; i < clearCode; i++) {
161 | dict[i] = [i];
162 | }
163 | dict[clearCode] = [];
164 | dict[eoiCode] = null;
165 |
166 | };
167 |
168 | var code;
169 | var last;
170 |
171 | while (true) {
172 | last = code;
173 | code = readCode(codeSize);
174 |
175 | if (code === clearCode) {
176 | clear();
177 | continue;
178 | }
179 | if (code === eoiCode) break;
180 |
181 | if (code < dict.length) {
182 | if (last !== clearCode) {
183 | dict.push(dict[last].concat(dict[code][0]));
184 | }
185 | }
186 | else {
187 | if (code !== dict.length) throw new Error('Invalid LZW code.');
188 | dict.push(dict[last].concat(dict[last][0]));
189 | }
190 | output.push.apply(output, dict[code]);
191 |
192 | if (dict.length === (1 << codeSize) && codeSize < 12) {
193 | // If we're at the last code and codeSize is 12, the next code will be a clearCode, and it'll be 12 bits long.
194 | codeSize++;
195 | }
196 | }
197 |
198 | // I don't know if this is technically an error, but some GIFs do it.
199 | //if (Math.ceil(pos / 8) !== data.length) throw new Error('Extraneous LZW bytes.');
200 | return output;
201 | };
202 |
203 |
204 | // The actual parsing; returns an object with properties.
205 | var parseGIF = function (st, handler) {
206 | handler || (handler = {});
207 |
208 | // LZW (GIF-specific)
209 | var parseCT = function (entries) { // Each entry is 3 bytes, for RGB.
210 | var ct = [];
211 | for (var i = 0; i < entries; i++) {
212 | ct.push(st.readBytes(3));
213 | }
214 | return ct;
215 | };
216 |
217 | var readSubBlocks = function () {
218 | var size, data;
219 | data = '';
220 | do {
221 | size = st.readByte();
222 | data += st.read(size);
223 | } while (size !== 0);
224 | return data;
225 | };
226 |
227 | var parseHeader = function () {
228 | var hdr = {};
229 | hdr.sig = st.read(3);
230 | hdr.ver = st.read(3);
231 | if (hdr.sig !== 'GIF') throw new Error('Not a GIF file.'); // XXX: This should probably be handled more nicely.
232 | hdr.width = st.readUnsigned();
233 | hdr.height = st.readUnsigned();
234 |
235 | var bits = byteToBitArr(st.readByte());
236 | hdr.gctFlag = bits.shift();
237 | hdr.colorRes = bitsToNum(bits.splice(0, 3));
238 | hdr.sorted = bits.shift();
239 | hdr.gctSize = bitsToNum(bits.splice(0, 3));
240 |
241 | hdr.bgColor = st.readByte();
242 | hdr.pixelAspectRatio = st.readByte(); // if not 0, aspectRatio = (pixelAspectRatio + 15) / 64
243 | if (hdr.gctFlag) {
244 | hdr.gct = parseCT(1 << (hdr.gctSize + 1));
245 | }
246 | handler.hdr && handler.hdr(hdr);
247 | };
248 |
249 | var parseExt = function (block) {
250 | var parseGCExt = function (block) {
251 | var blockSize = st.readByte(); // Always 4
252 | var bits = byteToBitArr(st.readByte());
253 | block.reserved = bits.splice(0, 3); // Reserved; should be 000.
254 | block.disposalMethod = bitsToNum(bits.splice(0, 3));
255 | block.userInput = bits.shift();
256 | block.transparencyGiven = bits.shift();
257 |
258 | block.delayTime = st.readUnsigned();
259 |
260 | block.transparencyIndex = st.readByte();
261 |
262 | block.terminator = st.readByte();
263 |
264 | handler.gce && handler.gce(block);
265 | };
266 |
267 | var parseComExt = function (block) {
268 | block.comment = readSubBlocks();
269 | handler.com && handler.com(block);
270 | };
271 |
272 | var parsePTExt = function (block) {
273 | // No one *ever* uses this. If you use it, deal with parsing it yourself.
274 | var blockSize = st.readByte(); // Always 12
275 | block.ptHeader = st.readBytes(12);
276 | block.ptData = readSubBlocks();
277 | handler.pte && handler.pte(block);
278 | };
279 |
280 | var parseAppExt = function (block) {
281 | var parseNetscapeExt = function (block) {
282 | var blockSize = st.readByte(); // Always 3
283 | block.unknown = st.readByte(); // ??? Always 1? What is this?
284 | block.iterations = st.readUnsigned();
285 | block.terminator = st.readByte();
286 | handler.app && handler.app.NETSCAPE && handler.app.NETSCAPE(block);
287 | };
288 |
289 | var parseUnknownAppExt = function (block) {
290 | block.appData = readSubBlocks();
291 | // FIXME: This won't work if a handler wants to match on any identifier.
292 | handler.app && handler.app[block.identifier] && handler.app[block.identifier](block);
293 | };
294 |
295 | var blockSize = st.readByte(); // Always 11
296 | block.identifier = st.read(8);
297 | block.authCode = st.read(3);
298 | switch (block.identifier) {
299 | case 'NETSCAPE':
300 | parseNetscapeExt(block);
301 | break;
302 | default:
303 | parseUnknownAppExt(block);
304 | break;
305 | }
306 | };
307 |
308 | var parseUnknownExt = function (block) {
309 | block.data = readSubBlocks();
310 | handler.unknown && handler.unknown(block);
311 | };
312 |
313 | block.label = st.readByte();
314 | switch (block.label) {
315 | case 0xF9:
316 | block.extType = 'gce';
317 | parseGCExt(block);
318 | break;
319 | case 0xFE:
320 | block.extType = 'com';
321 | parseComExt(block);
322 | break;
323 | case 0x01:
324 | block.extType = 'pte';
325 | parsePTExt(block);
326 | break;
327 | case 0xFF:
328 | block.extType = 'app';
329 | parseAppExt(block);
330 | break;
331 | default:
332 | block.extType = 'unknown';
333 | parseUnknownExt(block);
334 | break;
335 | }
336 | };
337 |
338 | var parseImg = function (img) {
339 | var deinterlace = function (pixels, width) {
340 | // Of course this defeats the purpose of interlacing. And it's *probably*
341 | // the least efficient way it's ever been implemented. But nevertheless...
342 | var newPixels = new Array(pixels.length);
343 | var rows = pixels.length / width;
344 | var cpRow = function (toRow, fromRow) {
345 | var fromPixels = pixels.slice(fromRow * width, (fromRow + 1) * width);
346 | newPixels.splice.apply(newPixels, [toRow * width, width].concat(fromPixels));
347 | };
348 |
349 | // See appendix E.
350 | var offsets = [0, 4, 2, 1];
351 | var steps = [8, 8, 4, 2];
352 |
353 | var fromRow = 0;
354 | for (var pass = 0; pass < 4; pass++) {
355 | for (var toRow = offsets[pass]; toRow < rows; toRow += steps[pass]) {
356 | cpRow(toRow, fromRow)
357 | fromRow++;
358 | }
359 | }
360 |
361 | return newPixels;
362 | };
363 |
364 | img.leftPos = st.readUnsigned();
365 | img.topPos = st.readUnsigned();
366 | img.width = st.readUnsigned();
367 | img.height = st.readUnsigned();
368 |
369 | var bits = byteToBitArr(st.readByte());
370 | img.lctFlag = bits.shift();
371 | img.interlaced = bits.shift();
372 | img.sorted = bits.shift();
373 | img.reserved = bits.splice(0, 2);
374 | img.lctSize = bitsToNum(bits.splice(0, 3));
375 |
376 | if (img.lctFlag) {
377 | img.lct = parseCT(1 << (img.lctSize + 1));
378 | }
379 |
380 | img.lzwMinCodeSize = st.readByte();
381 |
382 | var lzwData = readSubBlocks();
383 |
384 | img.pixels = lzwDecode(img.lzwMinCodeSize, lzwData);
385 |
386 | if (img.interlaced) { // Move
387 | img.pixels = deinterlace(img.pixels, img.width);
388 | }
389 |
390 | handler.img && handler.img(img);
391 | };
392 |
393 | var parseBlock = function () {
394 | var block = {};
395 | block.sentinel = st.readByte();
396 |
397 | switch (String.fromCharCode(block.sentinel)) { // For ease of matching
398 | case '!':
399 | block.type = 'ext';
400 | parseExt(block);
401 | break;
402 | case ',':
403 | block.type = 'img';
404 | parseImg(block);
405 | break;
406 | case ';':
407 | block.type = 'eof';
408 | handler.eof && handler.eof(block);
409 | break;
410 | default:
411 | throw new Error('Unknown block: 0x' + block.sentinel.toString(16)); // TODO: Pad this with a 0.
412 | }
413 |
414 | if (block.type !== 'eof') setTimeout(parseBlock, 0);
415 | };
416 |
417 | var parse = function () {
418 | parseHeader();
419 | setTimeout(parseBlock, 0);
420 | };
421 |
422 | parse();
423 | };
424 |
425 | var SuperGif = function ( opts ) {
426 | var options = {
427 | //viewport position
428 | vp_l: 0,
429 | vp_t: 0,
430 | vp_w: null,
431 | vp_h: null,
432 | //canvas sizes
433 | c_w: null,
434 | c_h: null
435 | };
436 | for (var i in opts ) { options[i] = opts[i] }
437 | if (options.vp_w && options.vp_h) options.is_vp = true;
438 |
439 | var stream;
440 | var hdr;
441 |
442 | var loadError = null;
443 | var loading = false;
444 |
445 | var transparency = null;
446 | var delay = null;
447 | var disposalMethod = null;
448 | var disposalRestoreFromIdx = null;
449 | var lastDisposalMethod = null;
450 | var frame = null;
451 | var lastImg = null;
452 |
453 | var playing = true;
454 | var forward = true;
455 |
456 | var ctx_scaled = false;
457 |
458 | var frames = [];
459 | var frameOffsets = []; // elements have .x and .y properties
460 |
461 | var gif = options.gif;
462 | if (typeof options.auto_play == 'undefined')
463 | options.auto_play = (!gif.getAttribute('rel:auto_play') || gif.getAttribute('rel:auto_play') == '1');
464 |
465 | var onEndListener = (options.hasOwnProperty('on_end') ? options.on_end : null);
466 | var loopDelay = (options.hasOwnProperty('loop_delay') ? options.loop_delay : 0);
467 | var overrideLoopMode = (options.hasOwnProperty('loop_mode') ? options.loop_mode : 'auto');
468 | var drawWhileLoading = (options.hasOwnProperty('draw_while_loading') ? options.draw_while_loading : true);
469 | var showProgressBar = drawWhileLoading ? (options.hasOwnProperty('show_progress_bar') ? options.show_progress_bar : true) : false;
470 | var progressBarHeight = (options.hasOwnProperty('progressbar_height') ? options.progressbar_height : 25);
471 | var progressBarBackgroundColor = (options.hasOwnProperty('progressbar_background_color') ? options.progressbar_background_color : 'rgba(255,255,255,0.4)');
472 | var progressBarForegroundColor = (options.hasOwnProperty('progressbar_foreground_color') ? options.progressbar_foreground_color : 'rgba(255,0,22,.8)');
473 |
474 | var clear = function () {
475 | transparency = null;
476 | delay = null;
477 | lastDisposalMethod = disposalMethod;
478 | disposalMethod = null;
479 | frame = null;
480 | };
481 |
482 | // XXX: There's probably a better way to handle catching exceptions when
483 | // callbacks are involved.
484 | var doParse = function () {
485 | try {
486 | parseGIF(stream, handler);
487 | }
488 | catch (err) {
489 | doLoadError('parse');
490 | }
491 | };
492 |
493 | var doText = function (text) {
494 | toolbar.innerHTML = text; // innerText? Escaping? Whatever.
495 | toolbar.style.visibility = 'visible';
496 | };
497 |
498 | var setSizes = function(w, h) {
499 | canvas.width = w * get_canvas_scale();
500 | canvas.height = h * get_canvas_scale();
501 | toolbar.style.minWidth = ( w * get_canvas_scale() ) + 'px';
502 |
503 | tmpCanvas.width = w;
504 | tmpCanvas.height = h;
505 | tmpCanvas.style.width = w + 'px';
506 | tmpCanvas.style.height = h + 'px';
507 | tmpCanvas.getContext('2d').setTransform(1, 0, 0, 1, 0, 0);
508 | };
509 |
510 | var setFrameOffset = function(frame, offset) {
511 | if (!frameOffsets[frame]) {
512 | frameOffsets[frame] = offset;
513 | return;
514 | }
515 | if (typeof offset.x !== 'undefined') {
516 | frameOffsets[frame].x = offset.x;
517 | }
518 | if (typeof offset.y !== 'undefined') {
519 | frameOffsets[frame].y = offset.y;
520 | }
521 | };
522 |
523 | var doShowProgress = function (pos, length, draw) {
524 | if (draw && showProgressBar) {
525 | var height = progressBarHeight;
526 | var left, mid, top, width;
527 | if (options.is_vp) {
528 | if (!ctx_scaled) {
529 | top = (options.vp_t + options.vp_h - height);
530 | height = height;
531 | left = options.vp_l;
532 | mid = left + (pos / length) * options.vp_w;
533 | width = canvas.width;
534 | } else {
535 | top = (options.vp_t + options.vp_h - height) / get_canvas_scale();
536 | height = height / get_canvas_scale();
537 | left = (options.vp_l / get_canvas_scale() );
538 | mid = left + (pos / length) * (options.vp_w / get_canvas_scale());
539 | width = canvas.width / get_canvas_scale();
540 | }
541 | //some debugging, draw rect around viewport
542 | if (false) {
543 | if (!ctx_scaled) {
544 | var l = options.vp_l, t = options.vp_t;
545 | var w = options.vp_w, h = options.vp_h;
546 | } else {
547 | var l = options.vp_l/get_canvas_scale(), t = options.vp_t/get_canvas_scale();
548 | var w = options.vp_w/get_canvas_scale(), h = options.vp_h/get_canvas_scale();
549 | }
550 | ctx.rect(l,t,w,h);
551 | ctx.stroke();
552 | }
553 | }
554 | else {
555 | top = (canvas.height - height) / (ctx_scaled ? get_canvas_scale() : 1);
556 | mid = ((pos / length) * canvas.width) / (ctx_scaled ? get_canvas_scale() : 1);
557 | width = canvas.width / (ctx_scaled ? get_canvas_scale() : 1 );
558 | height /= ctx_scaled ? get_canvas_scale() : 1;
559 | }
560 |
561 | ctx.fillStyle = progressBarBackgroundColor;
562 | ctx.fillRect(mid, top, width - mid, height);
563 |
564 | ctx.fillStyle = progressBarForegroundColor;
565 | ctx.fillRect(0, top, mid, height);
566 | }
567 | };
568 |
569 | var doLoadError = function (originOfError) {
570 | var drawError = function () {
571 | ctx.fillStyle = 'black';
572 | ctx.fillRect(0, 0, options.c_w ? options.c_w : hdr.width, options.c_h ? options.c_h : hdr.height);
573 | ctx.strokeStyle = 'red';
574 | ctx.lineWidth = 3;
575 | ctx.moveTo(0, 0);
576 | ctx.lineTo(options.c_w ? options.c_w : hdr.width, options.c_h ? options.c_h : hdr.height);
577 | ctx.moveTo(0, options.c_h ? options.c_h : hdr.height);
578 | ctx.lineTo(options.c_w ? options.c_w : hdr.width, 0);
579 | ctx.stroke();
580 | };
581 |
582 | loadError = originOfError;
583 | hdr = {
584 | width: gif.width,
585 | height: gif.height
586 | }; // Fake header.
587 | frames = [];
588 | drawError();
589 | };
590 |
591 | var doHdr = function (_hdr) {
592 | hdr = _hdr;
593 | setSizes(hdr.width, hdr.height)
594 | };
595 |
596 | var doGCE = function (gce) {
597 | pushFrame();
598 | clear();
599 | transparency = gce.transparencyGiven ? gce.transparencyIndex : null;
600 | delay = gce.delayTime;
601 | disposalMethod = gce.disposalMethod;
602 | // We don't have much to do with the rest of GCE.
603 | };
604 |
605 | var pushFrame = function () {
606 | if (!frame) return;
607 | frames.push({
608 | data: frame.getImageData(0, 0, hdr.width, hdr.height),
609 | delay: delay
610 | });
611 | frameOffsets.push({ x: 0, y: 0 });
612 | };
613 |
614 | var doImg = function (img) {
615 | if (!frame) frame = tmpCanvas.getContext('2d');
616 |
617 | var currIdx = frames.length;
618 |
619 | //ct = color table, gct = global color table
620 | var ct = img.lctFlag ? img.lct : hdr.gct; // TODO: What if neither exists?
621 |
622 | /*
623 | Disposal method indicates the way in which the graphic is to
624 | be treated after being displayed.
625 |
626 | Values : 0 - No disposal specified. The decoder is
627 | not required to take any action.
628 | 1 - Do not dispose. The graphic is to be left
629 | in place.
630 | 2 - Restore to background color. The area used by the
631 | graphic must be restored to the background color.
632 | 3 - Restore to previous. The decoder is required to
633 | restore the area overwritten by the graphic with
634 | what was there prior to rendering the graphic.
635 |
636 | Importantly, "previous" means the frame state
637 | after the last disposal of method 0, 1, or 2.
638 | */
639 | if (currIdx > 0) {
640 | if (lastDisposalMethod === 3) {
641 | // Restore to previous
642 | // If we disposed every frame including first frame up to this point, then we have
643 | // no composited frame to restore to. In this case, restore to background instead.
644 | if (disposalRestoreFromIdx !== null) {
645 | frame.putImageData(frames[disposalRestoreFromIdx].data, 0, 0);
646 | } else {
647 | frame.clearRect(lastImg.leftPos, lastImg.topPos, lastImg.width, lastImg.height);
648 | }
649 | } else {
650 | disposalRestoreFromIdx = currIdx - 1;
651 | }
652 |
653 | if (lastDisposalMethod === 2) {
654 | // Restore to background color
655 | // Browser implementations historically restore to transparent; we do the same.
656 | // http://www.wizards-toolkit.org/discourse-server/viewtopic.php?f=1&t=21172#p86079
657 | frame.clearRect(lastImg.leftPos, lastImg.topPos, lastImg.width, lastImg.height);
658 | }
659 | }
660 | // else, Undefined/Do not dispose.
661 | // frame contains final pixel data from the last frame; do nothing
662 |
663 | //Get existing pixels for img region after applying disposal method
664 | var imgData = frame.getImageData(img.leftPos, img.topPos, img.width, img.height);
665 |
666 | //apply color table colors
667 | img.pixels.forEach(function (pixel, i) {
668 | // imgData.data === [R,G,B,A,R,G,B,A,...]
669 | if (pixel !== transparency) {
670 | imgData.data[i * 4 + 0] = ct[pixel][0];
671 | imgData.data[i * 4 + 1] = ct[pixel][1];
672 | imgData.data[i * 4 + 2] = ct[pixel][2];
673 | imgData.data[i * 4 + 3] = 255; // Opaque.
674 | }
675 | });
676 |
677 | frame.putImageData(imgData, img.leftPos, img.topPos);
678 |
679 | if (!ctx_scaled) {
680 | ctx.scale(get_canvas_scale(),get_canvas_scale());
681 | ctx_scaled = true;
682 | }
683 |
684 | // We could use the on-page canvas directly, except that we draw a progress
685 | // bar for each image chunk (not just the final image).
686 | if (drawWhileLoading) {
687 | ctx.drawImage(tmpCanvas, 0, 0);
688 | drawWhileLoading = options.auto_play;
689 | }
690 |
691 | lastImg = img;
692 | };
693 |
694 | var player = (function () {
695 | var i = -1;
696 | var iterationCount = 0;
697 |
698 | var showingInfo = false;
699 | var pinned = false;
700 |
701 | /**
702 | * Gets the index of the frame "up next".
703 | * @returns {number}
704 | */
705 | var getNextFrameNo = function () {
706 | var delta = (forward ? 1 : -1);
707 | return (i + delta + frames.length) % frames.length;
708 | };
709 |
710 | var stepFrame = function (amount) { // XXX: Name is confusing.
711 | i = i + amount;
712 |
713 | putFrame();
714 | };
715 |
716 | var step = (function () {
717 | var stepping = false;
718 |
719 | var completeLoop = function () {
720 | if (onEndListener !== null)
721 | onEndListener(gif);
722 | iterationCount++;
723 |
724 | if (overrideLoopMode !== false || iterationCount < 0) {
725 | doStep();
726 | } else {
727 | stepping = false;
728 | playing = false;
729 | }
730 | };
731 |
732 | var doStep = function () {
733 | stepping = playing;
734 | if (!stepping) return;
735 |
736 | stepFrame(1);
737 | var delay = frames[i].delay * 10;
738 | if (!delay) delay = 100; // FIXME: Should this even default at all? What should it be?
739 |
740 | var nextFrameNo = getNextFrameNo();
741 | if (nextFrameNo === 0) {
742 | delay += loopDelay;
743 | setTimeout(completeLoop, delay);
744 | } else {
745 | setTimeout(doStep, delay);
746 | }
747 | };
748 |
749 | return function () {
750 | if (!stepping) setTimeout(doStep, 0);
751 | };
752 | }());
753 |
754 | var putFrame = function () {
755 | var offset;
756 | i = parseInt(i, 10);
757 |
758 | if (i > frames.length - 1){
759 | i = 0;
760 | }
761 |
762 | if (i < 0){
763 | i = 0;
764 | }
765 |
766 | offset = frameOffsets[i];
767 |
768 | tmpCanvas.getContext("2d").putImageData(frames[i].data, offset.x, offset.y);
769 | ctx.globalCompositeOperation = "copy";
770 | ctx.drawImage(tmpCanvas, 0, 0);
771 | };
772 |
773 | var play = function () {
774 | playing = true;
775 | step();
776 | };
777 |
778 | var pause = function () {
779 | playing = false;
780 | };
781 |
782 |
783 | return {
784 | init: function () {
785 | if (loadError) return;
786 |
787 | if ( ! (options.c_w && options.c_h) ) {
788 | ctx.scale(get_canvas_scale(),get_canvas_scale());
789 | }
790 |
791 | if (options.auto_play) {
792 | step();
793 | }
794 | else {
795 | i = 0;
796 | putFrame();
797 | }
798 | },
799 | step: step,
800 | play: play,
801 | pause: pause,
802 | playing: playing,
803 | move_relative: stepFrame,
804 | current_frame: function() { return i; },
805 | length: function() { return frames.length },
806 | move_to: function ( frame_idx ) {
807 | i = frame_idx;
808 | putFrame();
809 | }
810 | }
811 | }());
812 |
813 | var doDecodeProgress = function (draw) {
814 | doShowProgress(stream.pos, stream.data.length, draw);
815 | };
816 |
817 | var doNothing = function () {};
818 | /**
819 | * @param{boolean=} draw Whether to draw progress bar or not; this is not idempotent because of translucency.
820 | * Note that this means that the text will be unsynchronized with the progress bar on non-frames;
821 | * but those are typically so small (GCE etc.) that it doesn't really matter. TODO: Do this properly.
822 | */
823 | var withProgress = function (fn, draw) {
824 | return function (block) {
825 | fn(block);
826 | doDecodeProgress(draw);
827 | };
828 | };
829 |
830 |
831 | var handler = {
832 | hdr: withProgress(doHdr),
833 | gce: withProgress(doGCE),
834 | com: withProgress(doNothing),
835 | // I guess that's all for now.
836 | app: {
837 | // TODO: Is there much point in actually supporting iterations?
838 | NETSCAPE: withProgress(doNothing)
839 | },
840 | img: withProgress(doImg, true),
841 | eof: function (block) {
842 | //toolbar.style.display = '';
843 | pushFrame();
844 | doDecodeProgress(false);
845 | if ( ! (options.c_w && options.c_h) ) {
846 | canvas.width = hdr.width * get_canvas_scale();
847 | canvas.height = hdr.height * get_canvas_scale();
848 | }
849 | player.init();
850 | loading = false;
851 | if (load_callback) {
852 | load_callback(gif);
853 | }
854 |
855 | }
856 | };
857 |
858 | var init = function () {
859 | var parent = gif.parentNode;
860 |
861 | var div = document.createElement('div');
862 | canvas = document.createElement('canvas');
863 | ctx = canvas.getContext('2d');
864 | toolbar = document.createElement('div');
865 |
866 | tmpCanvas = document.createElement('canvas');
867 |
868 | div.width = canvas.width = gif.width;
869 | div.height = canvas.height = gif.height;
870 | toolbar.style.minWidth = gif.width + 'px';
871 |
872 | div.className = 'jsgif';
873 | toolbar.className = 'jsgif_toolbar';
874 | div.appendChild(canvas);
875 | div.appendChild(toolbar);
876 |
877 | parent.insertBefore(div, gif);
878 | parent.removeChild(gif);
879 |
880 | if (options.c_w && options.c_h) setSizes(options.c_w, options.c_h);
881 | initialized=true;
882 | };
883 |
884 | var get_canvas_scale = function() {
885 | var scale;
886 | if (options.max_width && hdr && hdr.width > options.max_width) {
887 | scale = options.max_width / hdr.width;
888 | }
889 | else {
890 | scale = 1;
891 | }
892 | return scale;
893 | }
894 |
895 | var canvas, ctx, toolbar, tmpCanvas;
896 | var initialized = false;
897 | var load_callback = false;
898 |
899 | var load_setup = function(callback) {
900 | if (loading) return false;
901 | if (callback) load_callback = callback;
902 | else load_callback = false;
903 |
904 | loading = true;
905 | frames = [];
906 | clear();
907 | disposalRestoreFromIdx = null;
908 | lastDisposalMethod = null;
909 | frame = null;
910 | lastImg = null;
911 |
912 | return true;
913 | }
914 |
915 | var calculateDuration = function() {
916 | return frames.reduce(function(duration, frame) {
917 | return duration + frame.delay;
918 | }, 0);
919 | }
920 |
921 | return {
922 | // play controls
923 | play: player.play,
924 | pause: player.pause,
925 | move_relative: player.move_relative,
926 | move_to: player.move_to,
927 |
928 | // getters for instance vars
929 | get_playing : function() { return playing },
930 | get_canvas : function() { return canvas },
931 | get_canvas_scale : function() { return get_canvas_scale() },
932 | get_loading : function() { return loading },
933 | get_auto_play : function() { return options.auto_play },
934 | get_length : function() { return player.length() },
935 | get_frames : function() { return frames },
936 | get_duration : function() { return calculateDuration() },
937 | get_duration_ms : function() { return calculateDuration() * 10 },
938 | get_current_frame: function() { return player.current_frame() },
939 | load_url: function(src,callback){
940 | if (!load_setup(callback)) return;
941 |
942 | var h = new XMLHttpRequest();
943 | // new browsers (XMLHttpRequest2-compliant)
944 | h.open('GET', src, true);
945 |
946 | if ('overrideMimeType' in h) {
947 | h.overrideMimeType('text/plain; charset=x-user-defined');
948 | }
949 |
950 | // old browsers (XMLHttpRequest-compliant)
951 | else if ('responseType' in h) {
952 | h.responseType = 'arraybuffer';
953 | }
954 |
955 | // IE9 (Microsoft.XMLHTTP-compliant)
956 | else {
957 | h.setRequestHeader('Accept-Charset', 'x-user-defined');
958 | }
959 |
960 | h.onloadstart = function() {
961 | // Wait until connection is opened to replace the gif element with a canvas to avoid a blank img
962 | if (!initialized) init();
963 | };
964 | h.onload = function(e) {
965 | if (this.status != 200) {
966 | doLoadError('xhr - response');
967 | }
968 | // emulating response field for IE9
969 | if (!('response' in this)) {
970 | this.response = new VBArray(this.responseText).toArray().map(String.fromCharCode).join('');
971 | }
972 | var data = this.response;
973 | if (data.toString().indexOf("ArrayBuffer") > 0) {
974 | data = new Uint8Array(data);
975 | }
976 |
977 | stream = new Stream(data);
978 | setTimeout(doParse, 0);
979 | };
980 | h.onprogress = function (e) {
981 | if (e.lengthComputable) doShowProgress(e.loaded, e.total, true);
982 | };
983 | h.onerror = function() { doLoadError('xhr'); };
984 | h.send();
985 | },
986 | load: function (callback) {
987 | this.load_url(gif.getAttribute('rel:animated_src') || gif.src,callback);
988 | },
989 | load_raw: function(arr, callback) {
990 | if (!load_setup(callback)) return;
991 | if (!initialized) init();
992 | stream = new Stream(arr);
993 | setTimeout(doParse, 0);
994 | },
995 | set_frame_offset: setFrameOffset
996 | };
997 | };
998 |
999 | return SuperGif;
1000 | }));
1001 |
1002 |
1003 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "libgif",
3 | "version": "0.0.3",
4 | "description": "JavaScript GIF parser and player forked from Buzzfeed",
5 | "main": "libgif.js",
6 | "scripts": {
7 | "test": "echo \"No active tests\" && exit 0"
8 | },
9 | "repository": {
10 | "type": "git",
11 | "url": "git+https://github.com/kelyvin/libgif-js.git"
12 | },
13 | "author": "",
14 | "license": "MIT",
15 | "bugs": {
16 | "url": "https://github.com/kelyvin/libgif-js/issues"
17 | },
18 | "homepage": "https://github.com/kelyvin/libgif-js#readme"
19 | }
20 |
--------------------------------------------------------------------------------
/rubbable.js:
--------------------------------------------------------------------------------
1 | /*
2 | RubbableGif
3 |
4 | Example usage:
5 |
6 |
7 |
8 |
16 |
17 | Image tag attributes:
18 |
19 | rel:animated_src - If this url is specified, it's loaded into the player instead of src.
20 | This allows a preview frame to be shown until animated gif data is streamed into the canvas
21 |
22 | rel:auto_play - Defaults to 1 if not specified. If set to zero, the gif will be rubbable but will not
23 | animate unless the user is rubbing it.
24 |
25 | Constructor options args
26 |
27 | gif Required. The DOM element of an img tag.
28 | auto_play Optional. Same as the rel:auto_play attribute above, this arg overrides the img tag info.
29 | max_width Optional. Scale images over max_width down to max_width. Helpful with mobile.
30 |
31 | Instance methods
32 |
33 | // loading
34 | load( callback ) Loads the gif into a canvas element and then calls callback if one is passed
35 |
36 | // play controls
37 | play - Start playing the gif
38 | pause - Stop playing the gif
39 | move_to(i) - Move to frame i of the gif
40 | move_relative(i) - Move i frames ahead (or behind if i < 0)
41 |
42 | // getters
43 | get_canvas The canvas element that the gif is playing in.
44 | get_playing Whether or not the gif is currently playing
45 | get_loading Whether or not the gif has finished loading/parsing
46 | get_auto_play Whether or not the gif is set to play automatically
47 | get_length The number of frames in the gif
48 | get_current_frame The index of the currently displayed frame of the gif
49 |
50 | For additional customization (viewport inside iframe) these params may be passed:
51 | c_w, c_h - width and height of canvas
52 | vp_t, vp_l, vp_ w, vp_h - top, left, width and height of the viewport
53 |
54 | */
55 | (function (root, factory) {
56 | if (typeof define === 'function' && define.amd) {
57 | define(['./libgif'], factory);
58 | } else if (typeof exports === 'object') {
59 | module.exports = factory(require('./libgif'));
60 | } else {
61 | root.RubbableGif = factory(root.SuperGif);
62 | }
63 | }(this, function (SuperGif) {
64 | var RubbableGif = function( options ) {
65 | var sup = new SuperGif( options );
66 |
67 | var register_canvas_handers = function () {
68 |
69 | var isvp = function(x) {
70 | return (options.vp_l ? ( x - options.vp_l ) : x );
71 | }
72 |
73 | var canvas = sup.get_canvas();
74 | var maxTime = 1000,
75 | // allow movement if < 1000 ms (1 sec)
76 | w = ( options.vp_w ? options.vp_w : canvas.width ),
77 | maxDistance = Math.floor(w / (sup.get_length() * 2)),
78 | // swipe movement of 50 pixels triggers the swipe
79 | startX = 0,
80 | startTime = 0;
81 |
82 | var cantouch = "ontouchend" in document;
83 |
84 | var aj = 0;
85 | var last_played = 0;
86 |
87 | canvas.addEventListener((cantouch) ? 'touchstart' : 'mousedown', function (e) {
88 | // prevent image drag (Firefox)
89 | e.preventDefault();
90 | if (sup.get_auto_play()) sup.pause();
91 |
92 | var pos = (e.touches && e.touches.length > 0) ? e.touches[0] : e;
93 |
94 | var x = (pos.layerX > 0) ? isvp(pos.layerX) : w / 2;
95 | var progress = x / w;
96 |
97 | sup.move_to( Math.floor(progress * (sup.get_length() - 1)) );
98 |
99 | startTime = e.timeStamp;
100 | startX = isvp(pos.pageX);
101 | });
102 |
103 | canvas.addEventListener((cantouch) ? 'touchend' : 'mouseup', function (e) {
104 | startTime = 0;
105 | startX = 0;
106 | if (sup.get_auto_play()) sup.play();
107 | });
108 |
109 | canvas.addEventListener((cantouch) ? 'touchmove' : 'mousemove', function (e) {
110 | e.preventDefault();
111 | var pos = (e.touches && e.touches.length > 0) ? e.touches[0] : e;
112 |
113 | var currentX = isvp(pos.pageX);
114 | currentDistance = (startX === 0) ? 0 : Math.abs(currentX - startX);
115 | // allow if movement < 1 sec
116 | currentTime = e.timeStamp;
117 | if (startTime !== 0 && currentDistance > maxDistance) {
118 | if (currentX < startX && sup.get_current_frame() > 0) {
119 | sup.move_relative(-1);
120 | }
121 | if (currentX > startX && sup.get_current_frame() < sup.get_length() - 1) {
122 | sup.move_relative(1);
123 | }
124 | startTime = e.timeStamp;
125 | startX = isvp(pos.pageX);
126 | }
127 |
128 | var time_since_last_play = e.timeStamp - last_played;
129 | {
130 | aj++;
131 | if (document.getElementById('tickles' + ((aj % 5) + 1))) document.getElementById('tickles' + ((aj % 5) + 1)).play();
132 | last_played = e.timeStamp;
133 | }
134 |
135 |
136 | });
137 | };
138 |
139 | sup.orig_load = sup.load;
140 | sup.load = function(callback) {
141 | sup.orig_load( function() {
142 | if (callback) callback();
143 | register_canvas_handers( sup );
144 | } );
145 | }
146 |
147 | return sup;
148 | }
149 |
150 | return RubbableGif;
151 | }));
--------------------------------------------------------------------------------