0

I need to make an N number of divs (represented as squares) to be arranged in a circle equidistant from each other.

I made the squares position: absolute so they will stack on top of each other on the center of the container. But from here I am not sure how to proceed in translating the divs into position. I tried dividing the full rotation of a circle (2 * Math.PI) by the number of squares N and using that value for translateY of each square, but it does not work.

const N = 10
const App = () => {
    return (
        <div className='container'>
            {new Array(N).fill(1).map((_, i) => (
                <Square key={i} index={i} />
            ))}
        </div>
    )
}

const Square = () => {
    const angle = (2 * Math.PI) / N;
    return (
        <div className='square'  />
    )
}

The image below is for reference.

For Reference

Echo
  • 521
  • 5
  • 16

1 Answers1

0

Taking the center of the circle as the origin, this is how you calculate the x and y coordinates for the center of each of the n squares:

const n = 4;
const radius = 100;

for (let i = 0; i < n; i ++) {
  const x = Math.cos(2 * Math.PI / n * i) * radius;
  const y = Math.sin(2 * Math.PI / n * i) * radius;
  
  console.log(x, y);
}
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156