DEV Community

prakasha
prakasha

Posted on

1

Building a Spin Wheel in React

Building a spin Wheel was in my to-do list for a very long time; finally, finally i was able to spend time on this.

Let's do this

Step 1: Calculate segmentAngle

Let's assume we want to show 6 items in the wheel. const itemsCount = 6;

segment angle
Divide the size of the wheel by the number of items => 360/6.
const segmentAngle = 360 / itemsCount;

Step 2: Identifying Radian & width from segmentAngle

You might be thinking, why do we need to identify radians 🧐?
I too had the same question. To find the exact width, we had to identify Radian.
Before even looking into this solution, i had used a random value as 45% 😂

Formula 1: radians = degrees * (π/180);
Formula 1: SegmentWidth = 2*radiusOfWheel*sin(segmentAngle)/2);

ref: Formula based on the central angle 🙏🏽

// Assume circle diameter is 300px
const radians = segmentAngle * (3.14 / 180); // 1.0466666666666669
const segmentWidth = 2 * 150 * Math.sin(1.0466666666666669 / 2); // 149.93103079293073
Enter fullscreen mode Exit fullscreen mode

Step 3: Set Height for segment
Wondering why it cannot be 100%, because if you do, then the UI breaks. 😹

We had to adjust the height of each segment to fit correctly inside the circle.
To make it look like a pizza slice, adjust height = 50% and transformY to 50%

partial implementation
This is how it will look like now.

Step 4: Implementing random rotation
Take a random number and multiply it by the segmentAngle to get a random rotation.
And add 5 spins to it.

const randomSpin = Math.floor(Math.random() * itemsCount) * segmentAngle;
const totalRotation = rotation + (360 * 5) + randomSpin; // 5 full rotations

Enter fullscreen mode Exit fullscreen mode

Below is my final result!

Sentry image

Make it make sense

Only the context you need to fix your broken code with Sentry.

Start debugging →

Top comments (0)

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay