vue 实现转盘抽奖
实现思路
使用Vue结合CSS动画和随机数生成实现转盘抽奖功能。核心是通过CSS控制转盘旋转,通过JavaScript计算旋转角度和结果判定。
基础HTML结构
<template>
<div class="lottery-container">
<div class="wheel" :style="wheelStyle">
<div class="wheel-item" v-for="(item, index) in prizes" :key="index"
:style="getItemStyle(index)">
{{ item.name }}
</div>
</div>
<button @click="startLottery" :disabled="isRotating">开始抽奖</button>
</div>
</template>
CSS样式
.wheel {
width: 300px;
height: 300px;
border-radius: 50%;
position: relative;
transition: transform 4s cubic-bezier(0.17, 0.67, 0.12, 0.99);
}
.wheel-item {
position: absolute;
width: 50%;
height: 50%;
transform-origin: 100% 100%;
left: 0;
top: 0;
display: flex;
align-items: center;
justify-content: center;
font-size: 14px;
color: #fff;
}
.lottery-container {
display: flex;
flex-direction: column;
align-items: center;
gap: 20px;
}
JavaScript逻辑
export default {
data() {
return {
prizes: [
{ name: '奖品1', color: '#FF5252' },
{ name: '奖品2', color: '#FF4081' },
{ name: '奖品3', color: '#E040FB' },
{ name: '奖品4', color: '#7C4DFF' },
{ name: '奖品5', color: '#536DFE' },
{ name: '奖品6', color: '#448AFF' }
],
rotation: 0,
isRotating: false
}
},
computed: {
wheelStyle() {
return {
transform: `rotate(${this.rotation}deg)`,
background: 'conic-gradient(' +
this.prizes.map((prize, i) =>
`${prize.color} ${i * (360/this.prizes.length)}deg ${(i+1) * (360/this.prizes.length)}deg`
).join(', ') + ')'
}
}
},
methods: {
getItemStyle(index) {
const angle = 360 / this.prizes.length
return {
transform: `rotate(${angle * index + angle/2}deg)`,
backgroundColor: this.prizes[index].color
}
},
startLottery() {
if (this.isRotating) return
this.isRotating = true
const rounds = 5 // 旋转圈数
const randomIndex = Math.floor(Math.random() * this.prizes.length)
const targetAngle = 360 * rounds + (360 - (360 / this.prizes.length) * randomIndex)
this.rotation = this.rotation % 360
this.rotation += targetAngle
setTimeout(() => {
this.isRotating = false
alert(`恭喜获得: ${this.prizes[randomIndex].name}`)
}, 4000)
}
}
}
优化建议
- 添加指针元素固定在转盘中心
- 增加音效增强体验
- 奖品数据可配置化,支持从后端获取
- 添加旋转过程中的防抖处理
- 支持自定义转盘尺寸和颜色
实现原理
旋转角度计算公式: $$ \text{总角度} = 360 \times \text{圈数} + (360 - \frac{360}{\text{奖品数量}} \times \text{随机索引}) $$
通过CSS的transition实现平滑旋转效果,cubic-bezier函数控制旋转速度曲线,使旋转过程有缓动效果更自然。旋转结束后根据最终角度计算落在哪个奖品区域。







