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

Wik*_*tor 5 javascript jquery animation canvas animated-gif

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

我尝试使用画布和精灵来做到这一点,但这非常具有挑战性。其实我也不太明白。我尝试过这个插件,但它的可能性有限。

所以我想知道是否可以使用 GIF 来做到这一点?也许我可以获取当前的动画帧并从该帧向后播放 gif?

lon*_*ght 6

是的,您可以使用一些 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>
Run Code Online (Sandbox Code Playgroud)

````

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());
})
Run Code Online (Sandbox Code Playgroud)

````