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

5
我想实现一个交互式的动画标志。默认情况下,它在第一帧。当鼠标悬停时,它向前播放并停在最后一帧。当鼠标离开时,它从最后一帧向前(反向)播放,停在第一帧。如果在向前动画期间鼠标离开,则获取当前帧并向后播放。
我尝试使用canvas和sprites实现这个目标,但是非常具有挑战性。事实上,我并不真正理解它。我尝试了this plugin,但其功能受限。
所以我想知道是否可以使用GIF来实现?也许我可以获取当前动画帧并从那个帧开始向后播放GIF?

1
这在GIF中不可能实现。最好的方法是使用sprite(精灵)。 - Rory McCrossan
一个GIF只有两个状态:播放或者不播放。无法通过程序暂停/倒放GIF。 - APAD1
2个回答

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>

```

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());
})

```


虽然这个链接可能回答了问题,但最好在此处包含答案的必要部分,并提供参考链接。仅有链接的答案如果链接页面发生更改可能会变得无效。 - Divyang Desai

0

我通过创建一个库来解决问题,该库接受一系列图像帧(精灵)并对其进行动画处理:

sprites.js


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接