Search code examples
cssreactjsrotationcss-animationstransform

CSS How do I force Spin Wheel to spin in one direction?



I created a simple spin wheel in React.
I have an int that outputs how many degrees the wheel should turn.
but the issue is transition seems to nullify this.
Ex. rotate(1080deg) should do a 3 full clock-wise rotation, but my spin wheel do random number of rotations and sometimes it just spins in the counter clock-wise direction.

I'm currently using: transition: transform 5s ease-in-out
Is there a way to guarantee a clock-wise rotation on the spin, and maybe at least make it do more rotation??

In SpinningWheel.js

# sorry entire file is very big and so I just cut and paste these
# react hook
const [WheelSpinner, setWheelSpinner] = useState({
    transform: 0
});

# onClick turn
let wheel_value = (Math.random() * 8).toFixed(2);
setWheelSpinner({ transform: `rotate(${wheel_value}turn)` });

# return
<div className='wheel--spinner' style={WheelSpinner}>
      {elements.map((element) => (
         <div className='wheel--number' key={element.id} ref={(el) => (refs.current[element.id] = el)} style={element.style}>
               <span>{element.content}</span>
         </div>
      ))}
</div>

In SpinningWheel.css:

.wheel--spinner {
    position: relative;
    width: 400px;
    height: 400px;
    background: #333;
    border-radius: 50%;
    overflow: hidden;
    transition: transform 5s ease-in-out;
}

I've been looking into @keyframes and such, but no real luck. Or at least doesn't seem to help out the basic ones I've tried with 50%, 100% transform.

chatGPT offered replacing 'ease-in-out' to 'linear' as solution, however I don't think that helped and I prefer ease-in-out with smooth transition.


Solution

  • Your question needs more clarification but I guess every time you click a random number will generate and spinner spins based on that.

    For a test case scenario consider first time random number is 2.5 so your spinner will be 2.5 times rotated. Second time you click random number is 1.5. At this state you have a spinner that is already rotated 2.5 times clockwise and now it must rotate 1 full turn counter clockwise to be 1.5 times rotated.

    You have to add previous rotation to current random number that is generated to get the result you want