How to tell if a gif has fully animated using jque

2019-05-21 18:16发布

问题:

If I have an animated gif that just runs a single animation, IE. it doesn't loop, is there a way using jquery, or anything for that matter, of telling when the animation is complete? I don't want to tell if the file if fully loaded, but that the animation has run its course.

回答1:

I think there is no way to detect it from javascript. I would choose a different solution instead.

Create a static image (can be in any format, JPEG, PNG, GIF), which has the frames of the original animation below each other. Like this:

┌───┐
│ 1 │
├───┤
│ 2 │
├───┤
│ 3 │
├───┤
│ 4 │
└───┘

Then you can create a <div/> for example with the dimensions of a frame and set this long static image as a background, then move the background in every nth milliseconds.

Tested code

$(function() {
  var width = 20, height = 20, frames = 3;

  var $div = $(document.createElement('div'))
    .css({
      backgroundImage: 'url(test.png)',
      width:  width + 'px',
      height: height + 'px'
    })
    .appendTo(document.body);

  var frame = 0;
  setInterval(function () {
    frame++;

    if (frame > frames) { frame = 0; }
    $div.css('background-position', '0 ' + -1 * frame * height + 'px');
  }, 250);
});

Update

Google did the same with the +1 buttons, but they did it in horizontally, not vertically, like the previous example: check it here.



回答2:

You can't. GIFs do not have event handlers.



回答3:

The answer is complex but it is indeed possible, however you will need a server-side language such as PHP (unless you know that the GIF will always be the same and have the same known duration).

The idea is that you read the contents of the GIF file, as an animated GIF is broken into frames that each have its own header. Read these headers to get the number of frames and the time between each frame.

You can then work out the duration of the animation (No. of frames x FPS). Using jQuery preload the GIF and when it is fully loaded display it and then wait for the duration of it's animation.