liveBook · Manning

requestAnimationFrame

As explained in Math for Web Design

requestAnimationFrame is a browser API method that schedules a callback to run before the next repaint.

requestAnimationFrame() schedules a callback for repeated animation updates. JavaScript can use each callback to calculate a new position, apply a CSS transform, and request the next frame. section 1.2.3 section 9.2.2

A typical animation loop connects timing, geometry, and presentation:

  • Update a changing value such as an angle; smaller speed values slow motion, larger values accelerate it, and negative values reverse direction. section 9.2.2
  • Calculate coordinates with Math.cos() and Math.sin(), using the center and radius to place the element on a circular path. section 9.2.2
  • Apply the coordinates through a CSS transform, then call requestAnimationFrame() again to continue the animation. section 9.2.2
  • Throttle scroll-driven updates by allowing one requestAnimationFrame() callback at a time. section 10.2.4
Listing 9.3 Circular path animation with JavaScript
function animateInACircle(element, centerX, centerY, radius, speed) {
    let angle = 0;

    function animate() {
        angle += speed;    #1
        const x = centerX + radius * Math.cos(angle);    #2
        const y = centerY + radius * Math.sin(angle);    #3

        element.style.transform = `translate(${x}px, ${y}px)`;    #4

        requestAnimationFrame(animate);    #5
    }

    animate();
}

Inspect a complete circular-motion loop that updates an angle, calculates x and y coordinates, transforms an element, and schedules the next frame. section 9.2.2

How Math for Web Design covers it

How deep it goes
Explains repeated callback scheduling within animation loops, but does not detail browser rendering internals.
Examples
Demonstrates circular motion and geometric parallax scrolling through JavaScript listings.
What you can do after
Build it from scratch for circular motion or throttle scroll-based parallax updates with JavaScript and CSS transforms.
How it connects
Connects requestAnimationFrame() with JavaScript animation, CSS transforms, trigonometric functions, scroll events, and parallax scrolling.

Also explained in

Compare how 2 books explain requestAnimationFrame →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Math for Web Design. The section links point to the parts of the book it draws on.