原文:http://danielcwilson.com/blog/2015/08/animations-part-3/
翻译:xiaomlove
在讨论了WAAPI的AnimationPlayer和时间控制之后,接着来说说多个动画和多个players。
一个元素多个动画
在上边的例子中,每个矩形div有三个动画在执行(transform变换,opacity透明度,以及颜色)。你可以在一个元素上多次调用animate,就像在CSS上允许多个animations。
使用CSS
#toAnimate { animation: pulse 1s, activate 3000ms, have-fun-with-it 2.5s; } @keyframes pulse { /* ... */ } @keyframes activate { /* ... */ } @keyframes have-fun-with-it { /* ... */ }
使用Web Animations API
var animated = document.getElementById('toAnimate'); var pulseKeyframes, //defined the keyframes here. activateKeyframes, haveFunKeyframes; var pulse = animated.animate(pulseKeyframes, 1000); //the second parameter as a number is a valid shorthand for duration var activate = animated.animate(activateKeyframes, 3000); var haveFunWithIt = animated.animate(haveFunKeyframes, 2500);
在Web Animations API中,所创建的三个AnimationPlayers,每个都可以是停止,播放,完成,取消,以及通过时间轴或者播放速度来控制。
获取所有AnimationPlayers
控制动画的播放与停止,但是在元素上调用animate()时又没有捕获AnimationPlayer,该如何做呢?
Web Animations API会自动创建一个默认的timeline,它就简单的存储在document的一个属性上:document.timeline。这个只在Firefox Nightly实现了,当然兼容库也是实现了的。这里边有很多东西可以做,但我们只关心它暴露的一个特殊的方法。
var players = document.timeline.getAnimations(); //returns array of all active (not finished and not canceled) animations
在上边的例子中,你能看到不少随机durations,delays,and transform的点,“Pause All”按钮调用getAnimations(),返回所有players,循环之即可进行停止。
可以试着编辑这个例子中的代码,将iterations由Infinity改为1,然后让动画播放接着按下pause按钮,你会发现getAnimations()不会返回任何players。这是因为所有的动画都结束了,这个方法只会返回那些处于runing或者paused状态的animations的player。
接下来…
在下一篇文章中,我们来看一下WAAPI下创建动画的不同方法(除了element.animate外还有很多方法),提示:document.timeline会有更精彩的出镜。