我正在开发一个Twitter应用程序,直接从Twitter引用图像。如何防止播放动画gif?
在火狐浏览器中,在页面末尾使用window.stop()
对我不起作用。
有没有更好的JavaScript黑客?最好,这应该适用于所有浏览器
发布于 2010-11-25 19:53:19
这不是一个跨浏览器的解决方案,但在火狐和opera中有效(在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);
}
}
发布于 2014-06-20 02:43:38
受@Karussell答案的启发,我写了Gifffer。在这里查看https://github.com/krasimir/gifffer
它会自动在你的Gif上添加停止/播放控制。
发布于 2014-07-12 05:47:47
为了改进Karussell的回答,这个版本应该是跨浏览器的,冻结所有图像,包括那些具有错误文件结尾的图像(例如,自动图像加载页面),并且不与原始图像的功能冲突,允许在原始图像上右击,就像它正在移动一样。
我会让它检测动画,但这比不管怎样冻结它们要密集得多。
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();
https://stackoverflow.com/questions/3688460
复制相似问题