vue实现点击旋转轮盘
实现点击旋转轮盘
使用Vue实现点击旋转轮盘可以通过结合CSS动画和Vue的数据绑定功能来完成。以下是一个完整的实现方案:
核心代码结构
<template>
<div class="wheel-container">
<div
class="wheel"
:style="{ transform: `rotate(${rotation}deg)` }"
@click="spinWheel"
>
<div class="wheel-item" v-for="(item, index) in items" :key="index">
{{ item }}
</div>
</div>
</div>
</template>
数据与状态管理
<script>
export default {
data() {
return {
rotation: 0,
isSpinning: false,
items: ['奖品1', '奖品2', '奖品3', '奖品4', '奖品5', '奖品6']
}
},
methods: {
spinWheel() {
if (this.isSpinning) return
this.isSpinning = true
const spinDuration = 3000
const targetRotation = this.rotation + 1800 + Math.random() * 360
this.rotation = targetRotation
setTimeout(() => {
this.isSpinning = false
const selectedIndex = this.calculateSelectedItem()
alert(`恭喜获得: ${this.items[selectedIndex]}`)
}, spinDuration)
},
calculateSelectedItem() {
const normalizedRotation = this.rotation % 360
const segmentAngle = 360 / this.items.length
return Math.floor(normalizedRotation / segmentAngle)
}
}
}
</script>
样式设计
<style scoped>
.wheel-container {
position: relative;
width: 300px;
height: 300px;
margin: 0 auto;
}
.wheel {
width: 100%;
height: 100%;
border-radius: 50%;
background: conic-gradient(
from 0deg,
#ff0000 0deg 60deg,
#00ff00 60deg 120deg,
#0000ff 120deg 180deg,
#ffff00 180deg 240deg,
#ff00ff 240deg 300deg,
#00ffff 300deg 360deg
);
position: relative;
transition: transform 3s cubic-bezier(0.17, 0.67, 0.12, 0.99);
cursor: pointer;
}
.wheel-item {
position: absolute;
width: 50px;
height: 50px;
text-align: center;
line-height: 50px;
color: white;
font-weight: bold;
transform-origin: 150px 150px;
}
</style>
实现要点
每个奖品项的位置需要通过计算确定,可以在mounted钩子中添加位置计算逻辑:
mounted() {
this.positionItems()
},
methods: {
positionItems() {
const angleStep = 360 / this.items.length
this.items.forEach((_, index) => {
const angle = index * angleStep
const element = this.$el.querySelectorAll('.wheel-item')[index]
element.style.transform = `rotate(${angle}deg) translate(100px) rotate(${-angle}deg)`
})
}
}
高级功能扩展
-
添加指针元素: 在轮盘中心添加固定指针,帮助识别最终选中的奖品。
-
自定义动画曲线: 调整
cubic-bezier参数实现更自然的旋转效果。 -
奖品权重控制: 修改旋转算法,使某些奖品更容易被选中。
-
API集成: 从后端获取奖品列表和权重数据。

这个实现提供了完整的点击旋转轮盘功能,包含动画效果和奖品选择逻辑,可以根据实际需求进一步定制样式和行为。






