以编程方式停止GIFanimation

我正在开发一个Twitter应用程序,它直接从Twitter上引用图像。 我怎样才能防止GIFanimation?

在页面末尾使用window.stop()在Firefox中不适用于我。

有更好的JavaScript黑客? 最好这应该适用于所有浏览器

这不是一个跨浏览器的解决scheme,但这在firefox和opera(而不是在ie8: – /)中工作。 从这里采取

 [].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); } } 

受@Karussell的回答启发,我写了“Gifffer”。 看看这里https://github.com/krasimir/gifffer

它会自动将停止/播放控制添加到您的Gif上。

为了改进Karussell的答案,这个版本应该是跨浏览器的,冻结所有图像,包括那些有不正确的文件结尾的图像(例如自动图像加载页面),并且不与原始图像的function冲突,允许原来的右键点击就好像它正在移动。

我会让它检测animation,但是这比仅仅冻结它们要密集得多。

 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(); 

这是一个黑客,但你可以尝试加载gif到一个iframe,并调用window.stop()从内部iframe(本身),一旦图像已经加载。 这可以防止页面的其他部分停止。