以编程方式停止 GIF 动画
问题描述:
我正在开发一个 Twitter 应用程序,它直接从 Twitter 引用图像.如何防止播放 gif 动画?
I am developing a Twitter application which references to the images directly from Twitter. How can I prevent animated gifs from being played?
在页面末尾使用 window.stop()
在 Firefox 中对我不起作用.
Using window.stop()
at the end of the page does not work for me in Firefox.
有更好的 JavaScript hack 吗?最好这应该适用于所有浏览器
Is there a better JavaScript hack? Preferable this should work for all browsers
答
这不是跨浏览器的解决方案,但它适用于 firefox 和opera(不适用于 ie8 :-/).取自此处
This is not a cross browser solution but this 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);
}
}