这是秒针的简化代码:
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
来暂停内容,但是如何阻止他们这样做对我来说却是不可理解的。
答案 0 :(得分:0)
好的。我想通了。
隐藏页面后,动画将以animationsPaused()
暂停。
当页面再次可见时,脚本:
setCurrentTime(0)
<path>
transform
属性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()
}
})