I’m a Libra. It is hard for me to make a decision especially at lunch time. Does it resonates to you? So I decided to make a lucky wheel to help me to choose a restaurant at lunch time. It will rotate base on your pressing time.
This is what we going to make:
Step 1: Start with create-react-app
and install react-spring
, run the command below:
npx create-react-app lucky-wheel
npm i react-spring --save
Step 2: Make a lucky wheel in App.js
.
We make a view box with height and width are 500px. So that we can easily calculate the center of circle is x:250 y:250
, svg
is like a coordinate system with origin at top left.
renderItems
is a function that calculate the coordinate from the center(x:250,y:250) to the edge of big circle, so that we can draw a red line to separate each region equally and place the text between two red lines. It seemed deceptively simple, we need to convert polar coordinate to Cartesian coordinate and deal with radian and degree.
With the OFFSET
value, we can make sure each time the starting point of the wheel is different. You can refresh the page and see it.
Step 3: Create a pressing area, with an animation of charging the power, the color change from hotpink
to red
.
In App.css
:
In App.js
:
We use react-spring
library here, we give the initial state: width: '0%', backgroundColor: 'hotpink'
and final state:width: '100%', backgroundColor: 'red'
to set
function, it will automatically generate the in-between value, addanimated.(html Tag)
to the region that should have the animation and access the value by props
from useSpring
.
Final Step: Pass the value to luck wheel and make it rotate.
In App.js
:
We add a power
and setPower
to store the power from user, and pass the setPower
to PressButton
, the width
in PressButton
is equal topower
(100 is max power and 0 is min power), we will pass the width
to setPower
when mouse up, once the power
changed it will trigger the set
function in App
and make the wheel spin. Also, there is a accumulator(acc
) to store the total power(total rotate degrees) and a map
function that map 0 to 100 to a range of rotate degree.
You can try it here.
Full code is in here.
Thanks for watching. See you.