如何在Web动画API完成之前立即暂停动画?

时间:2019-04-20 16:09:22

标签: javascript

我正在用JavaScript编写一个库,该库使用Web Animations API做一些动画。似乎默认情况下,动画制作完成后,所有内容都会在视觉上重置为动画开始之前的状态。

在完成状态或即将执行onfinish回调之前立即“暂停”动画的可靠方法是什么?

这里是一个例子:

var elem = document.querySelector('.pulse');
var animation = elem.animate(
  {
    opacity: [1, 0.5],
    transform: ['scale(1)', 'scale(0.5)']
  },
  {
    duration: 500
  }
);
animation.play();

// This works... but.. 10ms less than the duration?
// This cannot be very reliable...
setTimeout(function() {
  animation.pause();
}, 490);
<script src="https://rawgit.com/web-animations/web-animations-js/master/web-animations.min.js"></script>
<div class="pulse" style="width: 150px;">
  Hello world!
</div>

我想不使用setTimeout来完成此操作。在执行onfinish回调时,动画已经结束,并且看起来就像动画刚开始时一样。

2 个答案:

答案 0 :(得分:1)

为什么不将function clean(input) { let keep; return input.replace(/^\s*digraph\s+("[^"]*")\s*\{|\s*("[^"]+")\s*->\s*"[^"]+"\s*;|([^])/gm, (m, a, b, c) => a && (keep = a) || b === keep || c ? m : "" ); } // Example: var input = `digraph "com.a:test:jar:1.0" { "com.a:test:jar:1.0" -> "org.apache.httpcomponents:httpclient:jar:4.5.5:compile"; "com.a:test:jar:1.0" -> "com.google.code.gson:gson:jar:2.8.2:compile"; "com.a:test:jar:1.0" -> "info.picocli:picocli:jar:2.3.0:compile"; "com.a:test:jar:1.0" -> "log4j:log4j:jar:1.2.17:compile"; "com.a:test:jar:1.0" -> "org.xerial:sqlite-jdbc:jar:3.21.0:compile"; "org.apache.httpcomponents:httpclient:jar:4.5.5:compile" -> "org.apache.httpcomponents:httpcore:jar:4.4.9:compile" ; "org.apache.httpcomponents:httpclient:jar:4.5.5:compile" -> "commons-logging:commons-logging:jar:1.2:compile" ; "org.apache.httpcomponents:httpclient:jar:4.5.5:compile" -> "commons-codec:commons-codec:jar:1.10:compile" ; }` console.log(clean(input));CSS animation一起使用,从而使动画保持完成后的状态?

animation-fill-mode: forwards

答案 1 :(得分:1)

虽然@ andu-andrici的回答使我朝着正确的方向发展,但我仍在寻求Web Animations API中的解决方案。

解决方案是在fill: 'forwards'调用的第二个参数中向对象添加.animate()。像这样:

var elem = document.querySelector('.pulse');
var animation = elem.animate(
  {
    opacity: [1, 0.5],
    transform: ['scale(1)', 'scale(0.5)']
  },
  {
    duration: 500,
    fill: 'forwards'
  }
);
animation.play();
<script src="https://rawgit.com/web-animations/web-animations-js/master/web-animations.min.js"></script>
<div class="pulse" style="width: 150px;">
    Hello world!
</div>