How to tell if a gif has fully animated using jquery

你说的曾经没有我的故事 提交于 2019-12-06 12:00:50

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.

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!