How to stop an animated gif from looping
Not sure if this is the best way to answer everyone and it appears after all the previous answers and comments, but it seems to work.
I don't have much control over the gif. People post whatever gif they want as "thankyou.gif" in their account and then the "ThankYou" code triggers whatever they put there when a comment is submitted to the form they post. loop, some may, some may be short, some may be long. The solution I have come to is to tell people to take them 5 seconds, because when I'm going to pay them off and I don't care if they have loops or not.
Thanks for all the ideas.
source to share
Can you find out how long a gif takes to loop? if so, you can freeze the image like this:
pseudocode:
wait until the end of the image (when it is about to loop)
create a canvas element that has a static version of the gif as currently displayed drawn on it
hide gif
display canvas element in a way that makes it look like the gif froze
JavaScript:
var c = $("canvas")[0];
var w = c.width;
var h = c.height;
var img = $("img")[0];
setTimeout(function () {
c.getContext('2d').drawImage(img, 0, 0, w, h);
$(img).hide();
$(c).show();
},10000);
edit I forgot to add a link to the original answer I took, sorry
which does not take into account the time factor that you only need for one cycle
It was also mentioned that in some cases this approach is a trial one (it didn't actually work when I tried it in firefox right now ...). so here are some alternatives:
-
mentioned by mark: edit the gif itself to avoid the loop. this is the best option if you can. but I ran into situations where this was not possible (e.g. automatic generation of images by a third party).
-
instead of rendering a static image with a canvas, keep the static image version and switch to stop the loop . this is probably most of the problem as a canvas thing
source to share
Based on this answer , it's expensive, but it works. Let's say one cycle takes 2 seconds. In setTimeout after 2 seconds push in setInterval which will reset the source of the image every milliseconds:
setTimeout(function() {
setInterval(function() {
$('#img1').attr('src',$('#img1').attr('src'))
},1)
}, 2000)
again, maybe just a proof of concept, but here's a demo: http://jsfiddle.net/MEaWP/2/
source to share
It is actually possible to make a gif to stop after one iteration or any specific number of iterations, see the example below (if not already stopped) or in the jsfiddle .
To do this, you need to create a gif indicating the number of iterations. This can be done using Screen to Gif , it allows you to open a gif or a bunch of images and edit them frame by frame.
This solution also allows you to reset the animation imgElem.src = imgElem.src;
, but that doesn't work in MS IE / Edge.
source to share