From f735125ab24d06837d9d67e3485c9375e12da852 Mon Sep 17 00:00:00 2001 From: ArifKobel Date: Sat, 2 Mar 2024 15:13:55 +0100 Subject: [PATCH] feat: calculate coordinates on circle with respect to bounding client rect The `calculateCoordinatesOnCircle` function now accepts an additional parameter `boundingClientRect` which represents the bounding client rectangle of the element. This allows for accurate positioning of the coordinates on the circle taking into account the element's width and height. The `x` and `y` coordinates are now calculated based on the `centerX` and `centerY` values, which are derived from the original calculations. The `transform` property has been removed from the inline styles since it is no longer needed. Additionally, a `ref` has been added to the `div` element to reference the `orbitItemRef` for later use. --- packages/react-orbit/src/components/orbit.item.tsx | 9 +++++---- packages/react-orbit/src/utils/geometry.utils.ts | 12 ++++++++---- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/packages/react-orbit/src/components/orbit.item.tsx b/packages/react-orbit/src/components/orbit.item.tsx index 0a35e34..76287e9 100644 --- a/packages/react-orbit/src/components/orbit.item.tsx +++ b/packages/react-orbit/src/components/orbit.item.tsx @@ -25,7 +25,8 @@ export const OrbitItem = ({ ...rest }: OrbitItemProps) => { const [angle, setAngle] = React.useState(startAngle); - + const orbitItemRef = React.useRef(null); + useEffect(() => { const interval = setInterval(() => { setAngle((prevAngle) => (direction === 'clockwise' ? prevAngle + (step % 360) : prevAngle - (step % 360))); @@ -33,8 +34,8 @@ export const OrbitItem = ({ return () => clearInterval(interval); }, [step, delay]); - - const { x, y } = calculateCoordinatesOnCircle(radius, angle); + + const { x, y } = calculateCoordinatesOnCircle(radius, angle, orbitItemRef.current?.getBoundingClientRect() ?? new DOMRect()); return (
+ ref={orbitItemRef} {children}
); diff --git a/packages/react-orbit/src/utils/geometry.utils.ts b/packages/react-orbit/src/utils/geometry.utils.ts index 9654e32..7164ede 100644 --- a/packages/react-orbit/src/utils/geometry.utils.ts +++ b/packages/react-orbit/src/utils/geometry.utils.ts @@ -1,10 +1,14 @@ const DEGREE_TO_RADIAN_FACTOR = Math.PI / 180; -export const calculateCoordinatesOnCircle = (radius: number, angle: number): { x: number; y: number } => { +export const calculateCoordinatesOnCircle = (radius: number, angle: number, boundingClientRect: DOMRect): { x: number; y: number } => { const angleInRadians = angle * DEGREE_TO_RADIAN_FACTOR; - + const { width, height } = boundingClientRect; + const x = radius + (radius * Math.cos(angleInRadians)); + const y = radius + (radius * Math.sin(angleInRadians)); + const centerX = x - width / 2; + const centerY = y - height / 2; return { - x: radius + (radius * Math.cos(angleInRadians)), - y: radius + (radius * Math.sin(angleInRadians)), + x: centerX, + y: centerY, }; };