實(shí)現(xiàn)一個(gè)4*4d的宮格抽獎
第一步:UI實(shí)現(xiàn)正方形福压,可以循環(huán)渲染然后掏空中間部分,每個(gè)方格設(shè)置data-set
第二步:設(shè)置數(shù)組棋傍,根據(jù)上面的data-set排列方格的順序蚜锨,按照數(shù)組定義的順序,渲染active的樣式
第三步:設(shè)置定時(shí)器沙绝,每次‘亮’一個(gè)格子搏明,達(dá)到順時(shí)針的效果
第四步:設(shè)置速度,開始抽獎宿饱,速度由慢變快熏瞄;當(dāng)收到后端的獎品ids時(shí)(代碼是手動點(diǎn)擊使其結(jié)束脚祟,結(jié)束抽獎谬以,速度減慢
import React, { useRef } from 'react'
import styles from './styles.module.scss'
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
//調(diào)整順序
const currentIndex = [0, 1, 2, 3, 7, 11, 15, 14, 13, 12, 8, 4]
let timer = ''
//格子數(shù)量
let num = 0
//定時(shí)器間隔
let speed = 500
export default () => {
const prize = useRef()
const onStart = () => {
onDuring('start')
}
const onStop = () => {
//手動設(shè)置獎品為第五格
prize.current = 5
onDuring('end')
}
const onDuring = type => {
if (timer) clearTimeout(timer)
const items = document.querySelectorAll('.item')
if (num > 11) num = 0
items.forEach(el => {
//設(shè)置active樣式
el.dataset.index * 1 === currentIndex[num]
? (el.style.backgroundColor = 'yellow')
: (el.style.backgroundColor = 'pink')
})
if (type === 'start') {
//加速
if (speed > 100) speed -= 40
timer = setTimeout(() => {
onDuring('start')
}, speed)
} else {
timer = setTimeout(() => {
onDuring('end')
}, speed)
//減速
speed += 40
if (speed > 500 && num === prize.current) {
clearTimeout(timer)
}
}
num++
}
return (
<div>
<div className={styles.lottery}>
{arr.map((v, i) =>
[5, 6, 9, 10].indexOf(i) !== -1 ? (
<span key={i} className={styles.blank} />
) : (
<span key={i} className={`item ${styles.item}`} data-index={i}>
{v}
</span>
)
)}
<span className={styles.btn} onClick={onStart}>
抽獎
</span>
</div>
<span className={styles.stop} onClick={onStop}>
停止
</span>
</div>
)
}