vue实现点击旋转轮盘
实现点击旋转轮盘的步骤
HTML 结构
创建一个包含轮盘和触发按钮的容器,轮盘使用 div 元素并通过 CSS 控制样式。

<template>
<div class="wheel-container">
<div
class="wheel"
:style="{ transform: `rotate(${rotation}deg)` }"
@click="spinWheel"
>
<!-- 轮盘内容(可选) -->
</div>
<button @click="spinWheel">点击旋转</button>
</div>
</template>
JavaScript 逻辑
通过 Vue 的响应式数据控制旋转角度,使用 setTimeout 或动画库实现平滑过渡。

<script>
export default {
data() {
return {
rotation: 0, // 初始角度
isSpinning: false
};
},
methods: {
spinWheel() {
if (this.isSpinning) return;
this.isSpinning = true;
const targetRotation = this.rotation + 1800 + Math.random() * 360; // 随机旋转角度
const duration = 3000; // 动画时长(毫秒)
const startTime = performance.now();
const animate = (currentTime) => {
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
this.rotation = this.rotation + (targetRotation - this.rotation) * progress;
if (progress < 1) {
requestAnimationFrame(animate);
} else {
this.isSpinning = false;
}
};
requestAnimationFrame(animate);
}
}
};
</script>
CSS 样式
为轮盘添加过渡效果和视觉样式,确保旋转中心为轮盘中心。
<style>
.wheel-container {
display: flex;
flex-direction: column;
align-items: center;
}
.wheel {
width: 300px;
height: 300px;
border-radius: 50%;
background: conic-gradient(
red, orange, yellow, green, blue, indigo, violet
);
transition: transform 0.1s linear; /* 平滑过渡 */
cursor: pointer;
}
button {
margin-top: 20px;
padding: 10px 20px;
}
</style>
关键点说明
- 旋转控制:通过修改
rotation数据驱动 CSS 的transform属性实现旋转。 - 动画平滑性:使用
requestAnimationFrame逐帧更新角度,避免 CSS 过渡的局限性。 - 随机停止:通过
Math.random()生成随机终点角度,模拟抽奖效果。
扩展优化
- 分段奖励:根据最终角度计算奖励区间,可在
spinWheel方法末尾添加逻辑判断。 - 性能优化:对于复杂动画,可考虑使用 GSAP 等库替代原生实现。






