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!

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

πŸ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay