Home  >  Q&A  >  body text

How does requestAnimationFrame control frame rate?

I want to implement animation in canvas. Each frame of animation is drawn on Sprite and connected into one picture. I tried using setTimeout to implement animation and found that frames would jump. However, requestAnimationFrame cannot control the frame rate. I hope to draw 7 frames in 1s. what to do?

仅有的幸福仅有的幸福2734 days ago707

reply all(3)I'll reply

  • 过去多啦不再A梦

    过去多啦不再A梦2017-05-16 13:46:28

    requestAnimationFrame is called when the browser renders the next frame, so it can be considered that the calling rate of requestAnimationFrame is the refresh rate of the browser, which is generally 60 frames

    But when requestAnimationFrame calls callback, a timestamp parameter will be passed in. You can judge based on this parameter to process the frame rate you actually need

    For example, if you want 7 frames per second, you can write it like this

    let step = (timestamp, elapsed) => {
        if (elapsed > 1000 / 7) {
            //TO DO SOMETHING
            elapsed = 0
        }
        
        window.requestAnimationFrame(
            _timestamp => step(_timestamp, elapsed + _timestamp - timestamp)
        )
    }
    window.requestAnimationFrame(timestamp => step(timestamp, 0))

    reply
    0
  • PHP中文网

    PHP中文网2017-05-16 13:46:28

    It seems uncontrollable, the browser calculates it by itself

    reply
    0
  • 迷茫

    迷茫2017-05-16 13:46:28

    The refresh rate of 1s7 frames...is actually the effect of "skipping frames"...

    reply
    0
  • Cancelreply