简体   繁体   English

requestAnimationFrame动画循环

[英]requestAnimationFrame animation loop

I have the following code snippet: 我有以下代码片段:

function animate()
{
testdiv.style.transitionDuration="2500ms"
testdiv.style.transitionTimingFunction="linear"
testdiv.style.transform="rotate(45deg)"
window.requestAnimationFrame(animate)
}
window.requestAnimationFrame(animate)

This rotates the div 45 degrees and is working. 这会将div旋转45度并正在工作。
How can I turn this into an infinite animation loop so that the animation restarts automatically (from 0 degrees)? 如何将其变成无限的动画循环,以使动画自动(从0度开始)重新启动?

Hi try with below code. 嗨,尝试以下代码。

var FPS = 24;   //Frame per second. 
var prevTime,curTime;

function animate()
{
  curTime = new Date();
  if(prevTime === undefined || (curTime - prevTime) >= 1000/FPS)
  {
     testdiv.style.transitionDuration="2500ms"
     testdiv.style.transitionTimingFunction="linear"
     testdiv.style.transform="rotate(45deg)"

     prevTime = curTime;
  }

  window.requestAnimationFrame(animate);

}

window.requestAnimationFrame(animate)

It doesn't make sense to use requestAnimationFrame for either your current code, or the code you want to change to. 对于当前代码或要更改为的代码,都没有必要使用requestAnimationFrame

For the current code, you're setting a style and then letting CSS take over. 对于当前代码,您要设置样式,然后由CSS接管。 There's no need to do anything after time has passed. 时间过后,无需执行任何操作。

To change it to reset and repeat the loop, you want to trigger the new code when the animation has finished, not when the browser is ready to render a new frame. 要将其更改为重置并重复循环,您想在动画结束时而不是在浏览器准备渲染新帧时触发新代码。 To do that, listen for the transitionend event and then remove the transform value to set it back to the default. 为此,请侦听transitionend事件,然后删除转换值以将其设置回默认值。

 var testdiv = document.querySelector("div"); testdiv.addEventListener("transitionend", animate); setTimeout(animate, 100); function animate() { if (testdiv.style.transform) { testdiv.style.transform = ""; } else { testdiv.style.transform = "rotate(45deg)"; } } 
 body { padding: 100px; } div { transition-Duration: 2500ms; transition-Timing-Function: linear; } 
 <div>....</div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM