I've been attempting to create a React roulette spinner but I've encountered some issues with the transitions and functionality.
Here is the initial version of the algorithm:
The callback functions are triggered whenever the 'winner' prop changes
const slideRef = useRef(null);
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
const spinnerAnimation = useCallback(() => {
const numbers = {
0: 560,
11: -410,
5: 160,
10: 320,
6: 480,
9: 720,
7: 880,
8: 1050,
1: 1135,
14: 960,
2: 800,
13: 640,
3: 400,
12: 240,
4: 80,
};
const cycles = Math.floor(getRandomArbitrary(2, 4));
const dev = getRandomArbitrary(0, 80);
const scrollAmount = 480 + numbers[winner] + dev + 1200 * cycles;
slideRef.current.classList.remove('spin_animation');
slideRef.current.style = 'background-position-x: -212.5px';
setTimeout(() => {
slideRef.current.classList.add('spin_animation');
slideRef.current.style = `background-position-x: ${`-${scrollAmount}px
}, 10);
}, [winner]);
To achieve this, I'm using a background image and mapping out each distance: https://i.sstatic.net/9a5vJ.png
The issue arises when the spinner sometimes fails to stop at the correct number and resizing the browser window causes it to malfunction. Are there any alternative ways to create a spinner or suggestions on how to improve the current implementation?