liveBook · Manning

Math.cos

As explained in Math for Web Design

Math.cos is the JavaScript Math API method that returns the cosine of an angle expressed in radians.

To place a menu item on a circle, you need its horizontal position. Math.cos(angle) supplies the cosine of an angle in radians; multiplying it by the circle’s radius gives the horizontal offset from the center. Pair it with Math.sin(angle) for the vertical offset. section 9.2.1

Place menu items around a center

For each item, set angleStep = (2 * Math.PI) / items.length and angle = angleStep * index. Then calculate x = centerX + radius * Math.cos(angle) and y = centerY + radius * Math.sin(angle). Assign those values to the item’s CSS left and top properties; translate(-50%, -50%) centers the item on its calculated point. JavaScript accommodates a changing item count, while a fixed menu can use CSS cos() and sin(). section 9.2.1

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();
}

Circular animation repeats the same coordinate calculation: advance the angle, move the element, and request the next frame. A smaller speed value slows the motion; a negative value reverses it. section 9.2.2

Cosine also produces a back-and-forth swing. A pendulum effect calculates currentAngle = maxAngle * Math.cos(speed * t), then uses that angle to position an element below its pivot. For a pointer-responsive hover effect, Math.cos() contributes one rotation component after Math.atan2() determines the pointer’s angle from the element center. section 9.3.3 section 10.2.3

How Math for Web Design covers it

How deep it goes
Works through radius-and-angle coordinates and frame-by-frame updates rather than merely naming the method.
Examples
Uses a circular navigation menu, an orbiting element, a swinging sign, and a geometric hover effect.
What it assumes
Uses JavaScript element styling while deriving the angle step and coordinates needed for a circular layout.
What you can do after
Build it from scratch to position circular menus and animate elements along circular paths.
How it connects
Pairs Math.cos with Math.sin for circular coordinates and connects it to Math.atan2 for pointer-directed hover rotation.

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.