Stopping GIF Animation Programmatically

Kar*_*ell 69 html javascript animated-gif

I am developing a Twitter application which references to the images directly from Twitter. How can I prevent animated gifs from being played?

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

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

Kra*_*mir 60

受到@Karussell答案的启发,我写了Gifffer.在这里查看https://github.com/krasimir/gifffer

它会自动在你的Gif上添加停止/播放控制.

  • 希望我能+5这个. (3认同)

Kar*_*ell 50

这不是一个跨浏览器的解决方案,但这在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);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 它正在使用HTML5,据我所知,它应该适用于任何支持HTML5的浏览器.根据这个:http://www.deepbluesky.com/blog/-/browser-support-for-css3-and-html5_72/ IE仍然不支持它. (3认同)
  • 我认为*这只适用于本地动画GIF,而不是托管在不同域上的GIF动画 (3认同)
  • [Library](http://krasimirtsonev.com/blog/article/stop-autoplaying-your-gifs-stop-play-control)基于这个答案 (3认同)

Mak*_*aze 10

为了改进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();
Run Code Online (Sandbox Code Playgroud)


Jas*_*son 5

这有点麻烦,但您可以尝试将 gif 加载到 iframe 中,并window.stop()在图像加载后从 iframe 内部(自身)调用。这可以防止页面的其余部分停止。