vue实现转盘抽奖
Vue 实现转盘抽奖
基本思路
转盘抽奖的核心在于旋转动画和随机停止逻辑。通过CSS实现旋转效果,结合Vue的数据绑定控制旋转角度和停止时机。
准备工作
安装Vue项目并准备转盘图片或使用CSS绘制转盘。确保转盘被划分为多个等分区域,每个区域对应不同奖品。

实现步骤
HTML结构

<template>
<div class="wheel-container">
<div class="wheel" :style="wheelStyle" @click="startSpin">
<div class="wheel-item" v-for="(item, index) in prizes" :key="index" :style="getItemStyle(index)">
{{ item.name }}
</div>
</div>
<button @click="startSpin" :disabled="isSpinning">开始抽奖</button>
</div>
</template>
CSS样式
.wheel-container {
display: flex;
flex-direction: column;
align-items: center;
}
.wheel {
width: 300px;
height: 300px;
border-radius: 50%;
position: relative;
overflow: hidden;
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;
color: white;
font-weight: bold;
}
JavaScript逻辑
<script>
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,
isSpinning: false
}
},
computed: {
wheelStyle() {
return {
transform: `rotate(${this.rotation}deg)`
}
}
},
methods: {
getItemStyle(index) {
const angle = 360 / this.prizes.length
return {
transform: `rotate(${angle * index}deg)`,
backgroundColor: this.prizes[index].color
}
},
startSpin() {
if (this.isSpinning) return
this.isSpinning = true
const spinAngle = 360 * 5 + Math.floor(Math.random() * 360)
this.rotation = this.rotation % 360 + spinAngle
setTimeout(() => {
this.isSpinning = false
const prizeIndex = this.getPrizeIndex()
alert(`恭喜获得: ${this.prizes[prizeIndex].name}`)
}, 4000)
},
getPrizeIndex() {
const normalizedRotation = this.rotation % 360
const segmentAngle = 360 / this.prizes.length
return Math.floor((360 - normalizedRotation) / segmentAngle) % this.prizes.length
}
}
}
</script>
优化建议
- 添加指针元素,固定在转盘中心上方
- 实现更平滑的缓动效果,调整CSS的transition属性
- 增加音效增强用户体验
- 考虑使用GSAP等动画库实现更复杂的动画效果
- 添加API接口从服务器获取奖品数据
注意事项
- 旋转角度计算要考虑当前角度和完整旋转圈数
- 确保随机性公平,避免伪随机问题
- 移动端需要考虑触摸事件
- 性能优化,避免频繁的重绘和回流






