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
