簡體   English   中英

你能用 Javascript 控制 GIF 動畫嗎?

[英]Can you control GIF animation with Javascript?

是否可以使用 javascript 來控制GIF圖像的哪一幀正在顯示和/或停止動畫。 我希望能夠加載包含多個幀的GIF並且只顯示其中一個。

我知道我可以用很多單獨的圖像來做,但如果我可以用GIF做我想做的事,它只會是一個文件需要擔心。

您可以使用libgif庫。

它允許您啟動/停止 gif 並控制 gif 所在的幀。

<script type="text/javascript" src="./libgif.js"></script>
<img src="./example1_preview.gif" rel:animated_src="./example1.gif"
 width="360" height="360" rel:auto_play="1" rel:rubbable="1" />

<script type="text/javascript">
    $$('img').each(function (img_tag) {
        if (/.*\.gif/.test(img_tag.src)) {
            var rub = new SuperGif({ gif: img_tag } );
            rub.load(function(){
                console.log('oh hey, now the gif is loaded');
            });
        }
    });
</script>

(大部分代碼直接取自他們的示例)

我使用x-gif它非常酷且易於設置。

來自Github

<x-gif src="probably_cats.gif"></x-gif>

您可以將以下內容添加為屬性:

  • 播放模式:
    • speed="1.0" (默認模式)將速度乘以屬性值;
    • sync延遲播放到外部對象;
    • bpm="120" GIF 同步到給定的每分鍾節拍數;
  • 選項:

    • stopped阻止 GIF 動畫;

    • fill導致 GIF 擴展以覆蓋其容器;

    • n-times="3.0" (僅限速度模式)在設定的次數后停止播放(通過添加屬性stopped);
    • snap (僅限同步和 bpm 模式)而不是允許較長的 GIF 同步到多個節拍,而是強制它們只適合一個節拍;
    • ping-pong從前到后然后從后到前播放 GIF;
  • 調試:
    • debug打開 Gif Exploder 的調試輸出;
    • exploded停止播放,並並排渲染每一幀。

如果您可以將 gif 轉換為精靈表,您可以這樣做(使用 ImageMagick):

montage animation.gif -coalesce -tile x1 -geometry +0+0 -background None -quality 100 spritesheet.png

新圖像的尺寸甚至可能更小。

有了精靈表后,就可以使用 CSS 動畫了。 此處使用具有固定幀時間的動畫:

 var el = document.getElementById('anim'); function play() { el.style.animationPlayState = 'running'; } function pause() { el.style.animationPlayState = 'paused'; } function reset() { el.style.animation = 'none'; el.offsetHeight; /* trigger reflow to apply the change immediately */ el.style.animation = null; } function stop() { reset(); pause(); }
 #anim { background-image: url('https://i.stack.imgur.com/J5drY.png'); width: 250px; height: 188px; animation: anim 1.0s steps(10) infinite; } @keyframes anim { 100% { background-position: -2500px; } }
 <div id="anim" title="Animated Bat by Calciumtrice"></div> <button onclick="play()">Play</button> <button onclick="pause()">Pause</button> <button onclick="reset()">Reset</button> <button onclick="stop()">Stop</button>

如果您希望動畫不自動開始,請在animation結束規則中添加paused

您可以使用CSS sprites對單個圖像進行操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM