Let's move along a circle in JavaScript

By Eric Lewis

A circle is a shape where each x and y coordinate are equidistant from a center point.

JavaScript thankfully provides some useful math functions to help us calculate these coordinates to move something along a circle's path.

Meet my pal sine

Let's say that drawing a circle is a "cycle". The cycle starts on the right side of the circle and we'll draw counter clockwise.

Sine is a function that, provided a completion of the cycle, gives the y coordinate for a point on the circle in a range from -1 to 1.

Instead of measuring completion in percentage from 0-100%, we measure completion from 0π (Pi) to 2π because math. 0π complete is the point on the right side of the circle, ½π complete is the top, 1π complete is the left, and 1½π complete is the bottom.

Math.sin(cycleCompletion) = y coordinate from -1 to 1

Let's follow the y coordinate for our circle along the cycle!

Sine

-1 0 1

Cycle completion: π

Y value:

Mmm, look at that fluid animation as our y value floats up and down. It moves at a variable rate because the y value changes more slowly at the top and bottom parts of the circle while the x value is moving.

If we graph the sine value with time, we see the smooth curving oscillations of a sine wave.

But hey, we're not here to build a synthesizer, we're here to draw a circle!

Cosine, Sine's counterpoint

If sine is Daryl Hall, cosine is John Oates. While sine sings the melody on the Y mic, cosine is playing riffs on the X guitar in harmony.

Cosine is another function that, provided a completion of the cycle, gives the x coordinate for a point on the circle.

Cosine

-1 0 1

Cycle completion: π

X value:

Sine and cosine move in the same manner, swinging back and forth between -1 and 1. The difference is they are temporally shifted along the cycle. When sine is 0, cosine is 1. when sine is 1, cosine is 0. This matches our desired shape's design: at the top of the circle the x value is changing most rapidly, while the y value is barely changing.

Now, let's put sine and cosine together and play us a song.

X value (cosine):

Y value (sine):

Here's a code snippet for the above example. Have fun!