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.
Step 1: Calculate segmentAngle
Let's assume we want to show 6 items in the wheel. const itemsCount = 6;
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
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%
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
Below is my final result!
Top comments (0)