0

在浏览器选项卡之间切换时如何防止 SMIL 动画暂停?

我有 SVG 时钟,它使用<animatetransform>. 当您切换到另一个选项卡时,动画会冻结并且没有赶上它应该在的位置。我希望此动画在页面不可见时平稳运行,或者在页面再次可见时暂停并赶上。我可以把它转换成 CSS 动画,没关系。

这是秒针的简化代码:

HTML:

<svg viewbox="-250 -250 500 500" fill="none" stroke="#000">
<!-- ... -->
  <path id="Sec" stroke="#000" stroke-width="14" d="M0 0v-220">
    <animatetransform fill="freeze" additive="sum" attributename="transform" dur="60s" from="0" repeatcount="indefinite" to="360" type="rotate" />
  </path>
<!-- ... -->
</svg>

JS:

const date = new Date()
const sec = date.getSeconds()
document.getElementById('Sec').setAttribute('transform', `rotate(${(sec * 360 / 60) % 360})`)

我知道如何使用Page Visibility API来暂停事情,但如何阻止他们这样做对我来说是不可理解的。

4

1 回答 1

0

好的。我想出了那个。
当页面被隐藏时,动画会暂停animationsPaused()
当页面再次可见时,脚本:

  1. 获取新日期
  2. 重置动画时钟setCurrentTime(0)
  3. 更新<path> transform属性
  4. 开始动画unpauseAnimations()

HTML:

   <svg id="Watch" viewbox="-250 -250 500 500" fill="none" stroke="#000">
     <!-- ... -->
     <path id="Sec" stroke="#000" stroke-width="14" d="M0 0v-220">
       <animatetransform fill="freeze" additive="sum" attributename="transform" dur="60s" from="0" repeatcount="indefinite" to="360" type="rotate" />
     </path>
     <!-- ... -->
   </svg>

JS:

   const svg = document.getElementById('Watch')
   let date = new Date()
   const watch = () => {
     document.getElementById('Sec').setAttribute('transform', `rotate(${(date.getSeconds() * 360 / 60) % 360})`)
   }
   window.requestIdleCallback(() => watch())
   document.addEventListener('visibilitychange', () => {
     if (document.hidden) svg.pauseAnimations()
     else {
       date = new Date()
       svg.setCurrentTime(0)
       watch()
       svg.unpauseAnimations()
     }
   })
于 2020-11-06T15:37:15.207 回答