Stopping GIF Animations Programmatically

I am developing a Twitter application that links to images directly from Twitter. How can I prevent animated gifs from playing?

Using window.stop() at the end of the page does not work for me in Firefox.

Is there a better JavaScript hack? Preferably this should work for all browsers.

+52
javascript html animated-gif
Sep 10 '10 at 21:24
source share
4 answers

This is not a cross-browser solution, but it worked in firefox and opera (not in ie8: - /). Taken from here

 [].slice.apply(document.images).filter(is_gif_image).map(freeze_gif); function is_gif_image(i) { return /^(?!data:).*\.gif/i.test(i.src); } function freeze_gif(i) { var c = document.createElement('canvas'); var w = c.width = i.width; var h = c.height = i.height; c.getContext('2d').drawImage(i, 0, 0, w, h); try { i.src = c.toDataURL("image/gif"); // if possible, retain all css aspects } catch(e) { // cross-domain -- mimic original with all its tag attributes for (var j = 0, a; a = i.attributes[j]; j++) c.setAttribute(a.name, a.value); i.parentNode.replaceChild(c, i); } } 
+43
Nov 25 '10 at 11:53
source share

Inspired by @Karussell's answer, I wrote Gifffer. Take a look here https://github.com/krasimir/gifffer

It automatically adds stop / play controls on top of your Gif.

+46
Jun 19 '14 at 18:43
source share

In an attempt to improve Karussell's answer, this version should be a cross-browser, freezes all images, including those that have the wrong file (for example, automatic image loading pages), and does not contradict the function of the original image, allowing the right-click of the original, as if it moved.

I would make him detect animations, but this is much more intense than just freezing them independently.

 function createElement(type, callback) { var element = document.createElement(type); callback(element); return element; } function freezeGif(img) { var width = img.width, height = img.height, canvas = createElement('canvas', function(clone) { clone.width = width; clone.height = height; }), attr, i = 0; var freeze = function() { canvas.getContext('2d').drawImage(img, 0, 0, width, height); for (i = 0; i < img.attributes.length; i++) { attr = img.attributes[i]; if (attr.name !== '"') { // test for invalid attributes canvas.setAttribute(attr.name, attr.value); } } canvas.style.position = 'absolute'; img.parentNode.insertBefore(canvas, img); img.style.opacity = 0; }; if (img.complete) { freeze(); } else { img.addEventListener('load', freeze, true); } } function freezeAllGifs() { return new Array().slice.apply(document.images).map(freezeGif); } freezeAllGifs(); 
+7
Jul 11 '14 at 21:47
source share

This is a bit of a hack, but you can try loading the gif into an iframe and calling window.stop() from within the iframe (by itself) after loading the image. This will prevent the rest of the page from stopping.

+1
Sep 10 '10 at 21:33
source share



All Articles