实现一个4*4d的宫格抽奖
第一步:UI实现正方形,可以循环渲染然后掏空中间部分,每个方格设置data-set
第二步:设置数组,根据上面的data-set排列方格的顺序,按照数组定义的顺序,渲染active的样式
第三步:设置定时器,每次‘亮’一个格子,达到顺时针的效果
第四步:设置速度,开始抽奖,速度由慢变快;当收到后端的奖品ids时(代码是手动点击使其结束,结束抽奖,速度减慢
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]
//调整顺序
const currentIndex = [0, 1, 2, 3, 7, 11, 15, 14, 13, 12, 8, 4]
let timer = ''
//格子数量
let num = 0
//定时器间隔
let speed = 500
export default () => {
const prize = useRef()
const onStart = () => {
onDuring('start')
}
const onStop = () => {
//手动设置奖品为第五格
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 => {
//设置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>
)
}
网友评论