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 blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more