How to pause or play the animation of a GIF in Javascript?

Asked

Viewed 200 times

1

I am creating an HTML page that has an image format gif and a music display just below it.

<div><img src="imagem.gif"/></div>
<audio>
    <source src="musica.mp3" type="audio/mpeg"/>
</audio>

I would like to know how I can pause the animation of the image when the user pauses the music and proceed with the animation while playing the song. Example:

audio = document.querySelector("audio");

audio.onpause = stopGifAnimation;
audio.onplay = startGifAnimation;

It is possible to do this only with pure Javascript ?

  • I closed as dup, really I did not remember the other question, there are some examples without third party Libs, which can be much more interesting to most.

1 answer

2

I’d recommend trading the GIF for CSS Sprites (that you could even control a little with :hover or other pseudo-class) or by <canvas> (this would be more complicated)

But a quick fix is lib https://github.com/buzzfeed/libgif-js (that internally uses CANVAS), and has the controls:

Example with controls:

<img id="example1" src="inicial.jpg" rel:animated_src="seu_gif.gif" rel:auto_play="0" width="467" height="375" />

<script type="text/javascript">
    var sup1 = new SuperGif({ gif: document.getElementById('example1') } );
    sup1.load();
</script>

<hr>

<button onclick="sup1.pause();">Pause</button> |
<button onclick="sup1.play();">Play</button> |
<button onclick="sup1.move_to(0);">Restart</button> |
<button onclick="sup1.move_relative(1);">Step forward</button> |
<button onclick="sup1.move_relative(-1)">Step back</button>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.