Upload and play GIF images on canvas.
Sorry, the answer exceeded the size limit; I had to delete most of the detailed code comments.
I will not go into details, as the whole process is rather complicated.
The only way to get GIF animations in the canvas is to decode the GIF image in javascript. Fortunately, the format is not too complicated with data placed in blocks that contain image size, color pallets, time information, a comment box, and how to draw frames.
Custom download and GIF player.
The following example contains an object named GIF that will create custom-format GIFs from URLs that can play GIFs, just like video plays. You can also randomly access all GIF frames in any order.
There are many callbacks and options. The comments contain basic usage information, and the code shows how to load the gif. There are functions pause and play , seek(timeInSeconds) and seekFrame(frameNumber) , properties to control playSpeed and much more. There are no shuttle event events since access is immediate.
var myGif = GIF(); myGif.load("GIFurl.gif");
After loading
ctx.drawImage(myGif.image,0,0);
Or access frames through the frames buffer
ctx.drawImage(myGif.frames[0].image,0,0);
Go to the end of the GIF to see all the comments with options.
GIF must be the same domain or have a CORS header
In the demo version of the gif from the wiki commons and contains more than 250 frames, some low-maintenance devices will have problems with this, since each frame is converted to a full RGBA image, which makes the loaded GIF significantly larger than the size of the gif file.
Demo
Loads a gif displaying frames and the number of frames as loaded. When loading in the background, 100 particles with random access frames playing at independent speeds and independent directions are displayed.
A foreground image is a gif playing with a frame rate embedded in a file.
The code is as is, as an example, and NOT for commercial use.
const ctx = canvas.getContext("2d"); var myGif;
canvas { position: absolute; top: 0px; left: 0px; }
<canvas id="canvas"></canvas>
Run codeHide resultNOTES
This works for 99% gif. Sometimes you will find a gif that does not play correctly. Reason: (I never bothered to find out). Fix: transcode gif using a modern encoder.
There are some minor inconsistencies that need fixing. Over time, I will provide an example of CodePen with ES6 and an improved interface. Stay with us.