Giter VIP home page Giter VIP logo

gif.js's Introduction

gif.js

JavaScript GIF encoder that runs in your browser.

Uses typed arrays and web workers to render each frame in the background, it's really fast!

Demo - http://jnordberg.github.io/gif.js/

Works in browsers supporting: Web Workers, File API and Typed Arrays

Usage

Include gif.js found in dist/ in your page. Also make sure to have gif.worker.js in the same location.

var gif = new GIF({
  workers: 2,
  quality: 10
});

// add an image element
gif.addFrame(imageElement);

// or a canvas element
gif.addFrame(canvasElement, {delay: 200});

// or copy the pixels from a canvas context
gif.addFrame(ctx, {copy: true});

gif.on('finished', function(blob) {
  window.open(URL.createObjectURL(blob));
});

gif.render();

Options

Options can be passed to the constructor or using the setOptions method.

Name Default Description
repeat 0 repeat count, -1 = no repeat, 0 = forever
quality 10 pixel sample interval, lower is better
workers 2 number of web workers to spawn
workerScript gif.worker.js url to load worker script from
background #fff background color where source image is transparent
width null output image width
height null output image height
transparent null transparent hex color, 0x00FF00 = green
dither false dithering method, e.g. FloydSteinberg-serpentine
debug false whether to print debug information to console

If width or height is null image size will be deteremined by first frame added.

Available dithering methods are:

  • FloydSteinberg
  • FalseFloydSteinberg
  • Stucki
  • Atkinson

You can add -serpentine to use serpentine scanning, e.g. Stucki-serpentine.

addFrame options

Name Default Description
delay 500 frame delay
copy false copy the pixel data
dispose -1 frame disposal code. See GIF89a Spec

Acknowledgements

gif.js is based on:

Dithering code contributed by @PAEz and @panrafal

License

The MIT License (MIT)

Copyright (c) 2013 Johan Nordberg

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:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

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.

gif.js's People

Contributors

amilajack avatar anuragagarwal561994 avatar beager avatar dgo143 avatar dylanwenzlau avatar ebrensi avatar hdragomir avatar jnordberg avatar manuelodelain avatar panrafal avatar pjm0616 avatar zbryikt avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gif.js's Issues

build + npm update

Please build the lib and update npm.
There are a lot of merged PR since the 0.1.6 version.

Thanks a lot

compute deltas between frames

if you look at http://i.imgur.com/wypWt11.gif in GIMP you'll see why it fits into 3.95k, each frame is a delta from the previous frame.

i did a screen record with lossless codec at 60fps, compressed with gifsicle, which computed the background, frame deltas and i think also removed identical frames (which may be fast to identify with a hash or similar) or maybe it merged identical frames into longer-delayed single frames.

the original image size was tiny, each square block is a pixel. so if #2 is addressed, this would probably scale & encode in a < 100ms.

Can I control the render step by step?

for example,
I use canvas to show an animation.
when first frame is shown, i add this canvas to the GIF
then i show the second frame, and i add the second canvas to the GIF
and so on

Bower requires tags to install versions

Each version needs a corresponding tag to their versions, for bower to be able to successfully download pinned versions.

If I could pull request this, I would. Instead, for your convenience, anyone with push access can simply run this set of commands:

git tag v0.1.6 fe18289fa675333d36ba4cd9f86a56ffc20c3c5a
git tag v0.1.5 2a20675ff6c1daba4aa3641839db3147c38c29d5
git tag v0.1.4 faee238491302de05a1ed05e4fbe562738a76310
git tag v0.1.3 b69964025450110d4a0a99f9320331bd0a4ebb81
git tag v0.1.2 4ede1582155ec0084c654134f70c9a5e4e78a3f3
git tag v0.1.1 df58f6cd7658e39af8c2d06bfa4abcc108e4b177
git push --tags

This will then let bower download specific versions.

Compile latest source code

Hi, I'm sorry for the noob question, but what parts of the src folder should I include in my project if I want to get the ultimate commits?

Is there any way to "compile" so as to have the same as in the "dist" folder (gif.js and gif.worker.js)

Thanks a lot

Comment Extension Support

Awesome project!

I'm trying to figure out how to encode/decode the comment extension using this library? Is it supported? If not, what are the first steps in adding support for it, because I'd be happy to do so.

gif alpha issue

I have 2 frames png source files, wanna to generate a gif. I use this library and get the following gif:

hand-false

But I use rmagick library getting another different:

hand-true

Here are my 2 frames source files:

hand-false2
hand-false-1

Maybe it's about alpha issue.

Save to server via $_POST or $_FILE

I apologize in advance, I´m a noob.

When you retrieve the finished gif with 'createObjectURL(blob)', how can you save it to a gif in your SERVER? Do you have to change the blobURL to dataURL through ajax or can you use a html5 form? Is there a simple way of getting a .gif file (other than right clicking the image)?

Thanks for any help you can give and for your time. Cheers

Uncaught TypeError: Object [object Array] has no method 'set'

I'm adding frames from a processing.js sketch using gif.addImage(document.getElementById("my_canvas_id"), 30);

when I call gif.render, when the rendering is finished, I get a

rendering finished - filesize 4180kb gif.js:1
Uncaught TypeError: Object [object Array] has no method 'set' (gif.js:1)
a.finishRendering (gif.js:1)
a.frameFinished (gif.js:1)
c.onmessage (gif.js:1)

BlackBerry OS 10 issue

Hi,
First, thanks for your work regarding this project!
I tried your online demo in my BB phone, which has a webkit based browser, that supports all the requirements of this script, so it should work fine.
But on the main demo page the rendering stops at 0%.
I checked the console for errors and I found this:

spawning worker undefined gif.js:1
starting frame 1 of 1 gif.js:1
spawning worker undefined gif.js:1
starting frame 1 of 1 gif.js:1
spawning worker undefined gif.js:1
starting frame 1 of 4 gif.js:1
starting frame 2 of 4 gif.js:1
TypeError: 'undefined' is not an object (evaluating 'o[a][0]') /gif.js/gif.worker.js:1

The same error appears on the all pages performing conversion.
Any ideas?

Thanks in advance!
Best regards

Uncaught SyntaxError: Unexpected token <

Can anyone think of any reason I would be getting such output from gif.js?

spawning worker 0 gif.js:1
spawning worker 1 gif.js:1
starting frame 1 of 201 gif.js:1
starting frame 2 of 201 gif.js:1
Resource interpreted as Script but transferred with MIME type text/html: "file:///C:/Users/Vincent/Desktop/Software/Tools/Gyrographer/App/gif/". gif.js:1
Uncaught SyntaxError: Unexpected token <

Synchronous usage

Hi,

Is it possible to use gif.js synchronously, without "finished" event?

I wonder why do you create bindings with DOM etc. GIF encoder should be a tool, which receives ArrayBuffer (uncompressed image) and returns another ArrayBuffer (compressed image). If you want to make Canvas or an Image as an input, it should be built on top of GIF.js, not as the only input method.

Dithering

Still haven't got around to trying your stuff (web workers are tomorrow), but thought you might like a look at this....
https://dl.dropboxusercontent.com/u/3610419/JsGifStuff/Dithering.zip
...I did dithering!
Ive been looking around getting stuff for gif in js and was amazed no one had dithering so looked into it and found some nice AS to convert (the urls to the originals are in the source if you want to check my work).
Makes a real nice difference on gradients.
Sorry bout the awful test code ;) Im still in mucking around mode so I just throw what ever I need in there ;)
You want to look at the Bitmap.prototype.dither function at the end of dither.js.
Sorry bout the odd Bitmap class aswell ;) was just meant to give me something to work with and I know its odd.

Also while Im here, have a real good look at rgbQuant..it can do a MUCH better job than the other one alot of the time....dont give a dam if its slower....Im trying to get lots of options and they can decide if they want quick renders or production renders.

Side effects with other scripts using postmessage

Hello,

I just figured out that in some points, when there is an other plugin in the page using postmessage, it has some side effects with gifjs.

I have in my page a youtube html5 player, and when gifjs is also loaded (whatever the loading order), I got this error:

Uncaught SyntaxError: Failed to execute 'postMessage' on 'Window': Invalid target origin '' in a call to 'postMessage'. GIFEncoder.js:55

I will check with some other scripts using postmessage if it does the same side effects anyway and keep you updated if I find a workaround.

Cheers guys, thank you for this awesome work.

possible operation as a frameclient

would it be possible to have gif.js operate as a frameclient? (http://en.wikipedia.org/wiki/Frameserver)

i have a canvas animation that uses a single canvas element to draw separate frames. since gif.addImage does not extract ImageData when called, it is impossible to utilize different frames from the same canvas element. alternatively, .addImage can be made to accept extracted ImageData as well.

it would likely be easy, but memory-hungry to hold the imageData of all frames until .render() is called, but if the frame processing can be made eager instead of lazy, then a frameserver can stream frames from the same canvas element with the overhead dictated instead by worker count, cpu speed, encoder efficiency and config.

thanks!

setDelay with very small delay returns to default?

Let me say to start that I'm not even sure I'm right on this. I'm seeing some behavior but I don't have a deep enough understanding of the gif spec to know if what I think is true, is.

That said: It looks like when someone uses setDelay with a delay ms < 5 it rounds down to 0, which is the default, and I think is not "run as fast as possible"? I'm not sure on that, but I'm seeing that gifs seem to run a little slow when they come out.

No idea if that's right, just wanted to run it by you.

Screenshot bug when canvas fillStyle is black(#000000)

image

<canvas width="400" height="300" id="canvas"></canvas>
<img id="img">
var gif = new GIF({
  workers: 2,
  quality: 10,
  width: 400,
  height: 300,
  transparent: true
})
gif.on('finished', function(blob) {
  var img = document.getElementById('img')
  img.src = URL.createObjectURL(blob)
})
var canvasEl = document.getElementById('canvas');
var ctx = canvasEl.getContext('2d');

// set fill color of context
ctx.fillStyle = 'black';
ctx.fillRect(100, 100, 20, 20);
// ctx.fillStyle = '#000002';
// ctx.fillRect(200, 200, 20, 20);
ctx.fillStyle = 'red';
ctx.fillRect(200, 100, 20, 20);
gif.addFrame(ctx, {
  delay: 10,
  copy: true
})
gif.render()

Slow speed on WebKit Browsers

Hi.
When using Firefox the rendering proccess is very fast, but when using wekbit browser ( Chrome or Opera ) the speed is way slower. Why is that and is there something we can do about it?

Thanks.

Breaking down gif.js into smaller modules

This is less of an issue and more of a notice.

This weekend as part of Node Knockout, I implemented gifsockets in JavaScript.

http://console-log.2013.nodeknockout.com/

I started from gif.js for the GIF encoding but had to fork it significantly for stream-like behavior (it was a hackathon after all) and performance.

I want to formalize the work and edits for gifsockets into the appropriate node modules. As a result, each class (e.g. GifEncoder, TypedNeuQuant, LZWEncoder) will need to become its own repo and node module.

I would not be opposed to collaborating but I think this is following a different direction than gif.js which is more targeted at the browser.

Preserve transparency

Is it possible to preserve the transparency of imported pngs?

Edit: This is exactly my issue: #46

Example Uses?

This project seems interesting. Could you share some examples of how people are using it?

browser shims

I've had some experience with workers doing communistjs here are some things I learned:

  • workers are specified in the script but resolved relative to the html, i.e. calling your script as js/gif.js and gif.js would be different. My solution has been to surround the whole script in an if else clause which checks for typeof document === "undefined" and the script calls itself as the worker script, this also ends up being more portable.
  • transferable objects on typed array buffers is fast if you don't have to waste time converting to them, considering you already using typed arrays this could speed things up...
  • BUT Internet Explorer 10 will throw an error if you have an array as the second argument to post message (which you need for transferable objects) so you need to figure out how to deal with that.
  • IE 10 also doesn't have Uint8ClampedArray arrays which can be helpful for image data.
  • As far as I can tell workers simply process all messages they get in the order they get them and I have yet to conclusively figure out whether a queue type system like you have (and I have in some of my apps) actually has an advantage over just randomly spewing the data at an array of workers ala workers[~~(Math.random()*workers.length)].postMessage. The queue does have an advantage when the data processing times are very lumpy (some take much longer than others), though in other situations I have a suspicion the advantages may be outweighed by the overhead of the queue.

option to scale frames at encoder level

this could allow for much fast processing of frames since the encoder doesn't need to analyze pre-scaled-up images. nearest-neighbor upscale would be good for pixel art anims.

.

.

canvas transfer to gif meet problem

hi,I create a canvas element by reloading a remote script
then i use your code transfer to gif
for example get canvas element 2d context and gif.addFrame(canvasElement, {delay: 1000});
finally get a image of gif extension
unfortunately the gif image could not show annimate effect
I has seen your demo.first get canvas 2d context
then add
gif.addFrame(canvasElement, { delay: 1000 }); gif.on('finished', function(blob) { $("#canvasImage").attr("src",URL.createObjectURL(blob)); }); gif.render();
code segement
but my canvas element has been created
your idea that canvas element transfered to gif is getting 2d context and adding upper code segement
in short
getting 2d context and render gif need to operate at the same time
i don't know it is wrong.
code as it follows:

window.onload = function(){
var gif = new GIF({
workers: 4,
workerScript: 'PUBLIC/js/gif.worker.js',
quality: 15
});
var canvasElement = $("#anitOut canvas").eq(1)[0];
gif.addFrame(canvasElement, {
delay: 1000});
gif.on('finished', function(blob) {
$("#canvasImage").attr("src",URL.createObjectURL(blob));
});
gif.render();
};

online address: QQ登录界面

I'm looking forward to your reply. thank you,么么哒

Add frames at runtime

Hi,

Is it possible with your library to add frames to an existing gif at runtime? What I mean by that, is that I would receive a gif frame by socket.io and would like to append it to an existing gif animation. This would allow me to "stream" gif animation from the server.

Decimal width/height causes distorted output with images and canvas

ex.

If you specify {width: 213.5, height: 160}

and then do addFrame(image) or addFrame(canvas) the output be skewed and duplicated. If you specify 213 or 214 then it'll be fine.

I was getting this since I was rendering videos so I was specifying video.videoWidth / scaleFactor to downsize the video and it was making distorted gifs (the output looks skewed and you get the far right section of the picture on the far left).

Fails to execute 'getImageData' on 'CanvasRenderingContext2D'

I got Uncaught TypeError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The provided float value is non-finite. error while executing below snippet.

            var canvas = document.getElementById('canvas');
            canvas.width = 150;
            canvas.height = 150;

            var context = canvas.getContext('2d');
            context.font = "bold 70px Helvetica"
            context.textAlign = 'center'
            context.textBaseline = 'middle'
            context.lineWidth = 3;
            context.fillStyle = "rgb(0, 0, 0)";

            var gif = new GIF({
              workers: 2,
              quality: 10
            });

            gif.addFrame(context, {copy: true, delay: 200});

iOS - generated GIFs have transparent backgrounds?

So I'm using gif.js to write video frames to a canvas element to generate an animated GIF. That's all good on desktop, everything works great, GIF is perfect.

But I'm attempting to roll out a version working on the iPad (with iOS 8), and the bug I'm getting is super weird - essentially, the GIF will have random blocks of transparent background that don't appear on the desktop version. I've set background in my options like so background: 0x000000 but even with that, no good, still transparency. I've even written a solid black background to the canvas element using JS (which is then written over by the video frames), but when rendering, it still shows up as transparent.

Just throwing this out there as it's very peculiar and happens to ever GIF I create on mobile Safari using gif.js.

gif libraries

Hi Johan,

You said I was confusing gif libraries ?

Is there one I should be using instead of yours ?

thanks !

Using with requirejs

Hi,
I'm trying to use this library with require. I have added both files (gif and gif.worker) to the define and confirmed they are loaded in order (with a shim). The problem is, everytime I call render, it tries to import it by URL still:

10:55:26.393 spawning worker 0 gif.js:1:3912
10:55:26.384 ReferenceError: index is not defined
10:55:26.439 GET 
http://192.168.215.150/gif.worker.js [HTTP/1.1 404 NOT FOUND 21ms]
10:55:26.453 NetworkError: Failed to load worker script at "gif.worker.js"

Require config is:

        'gif': '../libraries/gif/gif',
        'gifworker': '../libraries/gif/gif.worker',
        'gif': { exports: 'gif', deps: [] },
        'gifworker': { exports: 'gifworker', deps: ['gif'] },

If I change exports to 'gif.worker', I get:

g is undefined

Any ideas?

Stop/Destroy GIF objects while rendering

Is there any way to stop/destroy a GIF while it's rendering? Something like:

gif = new gifjs.GIF({
    workers: 8,
    quality: options.quality,
    repeat: 0,
    width: options.width,
    height: options.height,
    workerScript: chrome.runtime.getURL('scripts/vendor/gif.worker.js')
});

// add frames here
gif.addFrame(...

gif.render();

// oh god this is taking too long please help
gif.stop(); // or gif.destroy();

Could someone provide a simple demo to me?thanks!

i try below, but finished evnet is invoked. please help! gif.js version is 0.1.2.
<

  1. !DOCTYPE html>
  2. < html>
  3. < head lang="en">
  4. < meta charset="UTF-8">
    
  5. < title></title>
    
  6. < /head>
  7. < body>
  8. < div>
  9. <i mg src="img/anim1.jpg" id="img1"/>
    
  10. < /div>
  11. </script>
  12. </script>
  13. window.onload = function () {
  14.     v ar a = new Image();
    
  15.     a.src = "img/anim1.jpg";
    
  16.     a.onload = function () {
    
  17.         var gif2 = new GIF({
    
  18.             workers: 2,
    
  19.             quality: 10
    
  20.         });
    
  21.         gif2.addFrame(a);
    
  22.         gif2.on('finished', function (blob) {
    
  23.             alert(2);
    
  24.             // window.open(URL.createObjectURL(blob));
    
  25.         });
    
  26.         gif2.render();
    
  27.     };
    
  28. }
    
  29. < /script>
  30. < /body>
  31. < /html>

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.