By Eric Lewis
This is the code snippet for my article Let's move along a circle in JavaScript.
const circleEl = document.querySelector(".circle");
const cycleLengthInMilliseconds = 5000;
const circleWidth = 80;
const circleMargin = 10;
const frame = timestamp => {
// Completion of the circle's cycle in a range from 0 to 1
const cycleCompletion =
(timestamp % cycleLengthInMilliseconds) / cycleLengthInMilliseconds;
// Cosine is the horizontal (x) coordinate of the point
// on the circle in a range from -1 to 1, respective
// of the circle's completion cycle.
const cosine = Math.cos(cycleCompletion * Math.PI * 2);
// Since cosine is a range from -1 to 1, we map that range
// to the circle's bounds in the SVG artboard, 10 to 90.
const cosineMappedToArtboard = (cosine / 2 + 0.5) * circleWidth + circleMargin;
circleEl.setAttribute('cx', cosineMappedToArtboard);
// Cosine is the vertical (y) coordinate of the point
// on the circle in a range from -1 to 1, respective
// of the circle's completion cycle.
const sine = Math.sin(cycleCompletion * Math.PI * 2);
// Since the range of sine is -1 to 1, we map that range
// to our circle's bounds in the SVG artboard, 10 to 90.
// We then subtract that value from the circleWidth and circleMargin,
// since the SVG drawing coordinates are flipped upside down
// compared to cartesian coordinates.
const sineMappedToArtboard = circleWidth + circleMargin - (sine / 2 + 0.5) * circleWidth;
circleEl.setAttribute('cy', sineMappedToArtboard);
window.requestAnimationFrame(frame);
};
window.requestAnimationFrame(frame);