Huan Huynh
Huan Huynh

Reputation: 477

React - calculate dots position in a circle

I have a wheel looks like this:

looks like this

I want to put the yellow bulbs on the circle, I'm thinking about using position: "absolute", top: xxx, left: yyy to achieve this, I guess that I will need some math to calculate corresponding top and left/right for each bulb but I dont know how.

Upvotes: 0

Views: 552

Answers (1)

Thomas Zimmermann
Thomas Zimmermann

Reputation: 1967

You could use the following functions to get X and Y coords based on the circle size, and its center.

Example for a circle with 100 px radius:

function getCircleY(radians, radius) {
  return Math.cos(radians) * radius;
}

function getCircleX(radians, radius) {
  return Math.sin(radians) * radius;
}

console.log("X coord at 0 degree:", getCircleX(0, 100));
console.log("Y coord at 0 degree:", getCircleY(0, 100));

console.log("X coord at 90 degree:", getCircleX(Math.PI / 2, 100));
console.log("Y coord at 90 degree:", getCircleY(Math.PI / 2, 100), "(= 0)");

console.log("X coord at 180 degree:", getCircleX(Math.PI, 100), "(= 0)");
console.log("Y coord at 180 degree:", getCircleY(Math.PI, 100));

// Angle as radians on a circle (radius 100px)
//      
//       x <-- 0°, 2π or 0 radians => x: 0px, y: 100px
//       |
//       |
// x-----0-----x <-- 90°, π / 2 radians => x: 100px, y: 0px
//       |
//       |
//       x <-- 180°, π radians => x: 0px, y: -100px

Check this out https://en.wikipedia.org/wiki/Radian

Upvotes: 2

Related Questions