用JS控制GIF动画。播放、停止、倒放

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

我想要实现的是交互式动画徽标。默认情况下,它位于第 1 帧。悬停时,它向前播放并在最后一帧停止。在 mouseleave 上,它从最后一帧播放到第一帧(向后)并在第一帧停止。如果在前进动画期间鼠标离开 -> 获取当前帧并向后播放。

我尝试使用 canvas 和精灵来做到这一点,但这非常具有挑战性。其实我也不是很懂。我尝试了 this plugin,但可能性有限。

所以我想知道是否可以使用 GIF 来实现?也许我可以获得当前动画帧并从该帧向后播放 gif?

是的,你可以用一些js库来控制gif,像这样: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(使用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());
})

```