user2386341
user2386341

Reputation: 25

Freezing Gif using JS at last frame

I'm trying to play a gif animation on my website and I want it to freeze on the last frame. I'm using this code found elsewhere to make it work, but it will either jump back to the first frame or disappear completely. Any help would be greatly appreciated.

<img src="http://s12.postimg.org/wq43xqknx/logoani.gif" id="img1" style="float: left"/>

setTimeout(function () {
setInterval(function () {
    $('#img1').attr('src', $('#img1').attr('src'))
}, 1)
}, 1000)

and here's the jsfiddle: http://jsfiddle.net/m6e6n/6/

Upvotes: 0

Views: 1272

Answers (1)

rupps
rupps

Reputation: 9887

At the moment JavaScript does not provide an interface to deal with the frames inside an animated GIF, you'll have to find a hacky way to do this but ...

I absolutely discourage you to use that script

Look what you're telling the CPU to execute every millisecond, that is, 1000 times per second:

  • Traverse the HTML document to find the element "img1"
  • Change its attribute "src" to ....
  • ... traverse again the HTML document for the same node
  • read its attribute src
  • assign it to the element found in 1
  • Then, the browser will go to the cache and find the image
  • Depending on the browser, the image may be decoded and rendered. It should start at frame 1, but who knows

So you can thank god if the browser still has some time for additional tasks.

Besides, assuming you don't care about overloading your users' computers, you'll have to finetune the timing very precisely to match the GIF framerate. And bad news is, if the framerate is quick, that's gonna be impossible to achieve across different browsers, or even different computers, let alone mobile devices.

So what can you do? I'd recommend you to play the GIF, then substitute it with a still image of the last frame. Just calculate how much time does one iteration take, then issue a timeout to change the gif with the still image.

Upvotes: 2

Related Questions