Search code examples
javascriptjqueryanimationcanvasanimated-gif

Control GIF animation with JS. Play, stop, play backwards


What I'm trying to achieve is interactive animated logo. By default it's on frame 1. When hovered, it plays forward and stops at last frame. On mouseleave it plays from last frame to first (backwards) and stops at first frame. If mouseleave during forward animation -> get current frame and play backwards.

I tried to do this using canvas and sprites but it's very challenging. In fact I don't really understand it. I tried this plugin, but it's possibilities are limited.

So I am wondering if I can do it using GIF? Maybe I could get current animation frame and play gif backwards from that frame?


Solution

  • Yes, you can control gif with some js lib, like this: https://github.com/buzzfeed/libgif-js

    html:

    ```

        <div id="controller-bar">
          <button id="backward" href="#">|< Step back </button>&nbsp;&nbsp;
          <button id="play" href="#"> Play | Pause </button>&nbsp;&nbsp;
          <button id="forward" href="#"> Step forward >|</button>
        </div>
    

    ```

    javascript(using jQuery):

    ```

    var gif = new SuperGif({
      gif: document.getElementById('example'),
      loop_mode: 'auto',
      auto_play: true,
      draw_while_loading: false,
      show_progress_bar: true,
      progressbar_height: 10,
      progressbar_foreground_color: 'rgba(0, 255, 4, 0.1)',
      progressbar_background_color: 'rgba(255,255,255,0.8)'
    
    });
    
    
    gif.load(function(){
      document.getElementById("controller-bar").style.visibility = 'visible';
      loaded = true;
      console.log('loaded');
    });
    
    
    $('button#backward').click(function(){
      console.log('current: ', gif.get_current_frame());
      var total_frames = gif.get_length();
      gif.pause();
      if(gif.get_current_frame() == 0) {
        gif.move_to(total_frames-1);
      } else {
        gif.move_relative(-1);
      }
      console.log('next: ', gif.get_current_frame());
    })
    
    
    $('button#play').click(function(){
      console.log('iam play');
      if(gif.get_playing()){
        gif.pause();
      } else {
        gif.play();
      }
    })
    
    $('button#forward').click(function(){
      console.log('current: ', gif.get_current_frame());
      gif.pause();
      gif.move_relative(1);
      console.log('next: ', gif.get_current_frame());
    })
    

    ```