vue实现旋转抽奖
Vue 实现旋转抽奖功能
旋转抽奖是一种常见的互动效果,可以通过 Vue 结合 CSS 动画和 JavaScript 实现。以下是具体实现方法:
准备工作
安装 Vue 3 并创建一个基础项目结构。确保项目中包含必要的依赖项,如 vue-router(如需页面跳转)和 axios(如需后端交互)。
创建抽奖组件
新建一个名为 LotteryWheel.vue 的组件文件,用于实现抽奖转盘的核心逻辑。
<template>
<div class="lottery-container">
<div class="wheel" :style="{ transform: `rotate(${rotation}deg)` }">
<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>
定义数据与样式
在 script 部分定义奖品数据和旋转状态:
<script>
export default {
data() {
return {
prizes: [
{ name: '奖品1', value: 1 },
{ name: '奖品2', value: 2 },
{ name: '奖品3', value: 3 },
{ name: '奖品4', value: 4 },
{ name: '奖品5', value: 5 },
{ name: '奖品6', value: 6 },
],
rotation: 0,
isRotating: false,
currentPrize: null,
};
},
methods: {
getItemStyle(index) {
const angle = 360 / this.prizes.length;
return {
transform: `rotate(${angle * index}deg)`,
};
},
},
};
</script>
添加 CSS 样式
在 style 部分添加转盘和奖品项的样式:
<style scoped>
.lottery-container {
display: flex;
flex-direction: column;
align-items: center;
}
.wheel {
width: 300px;
height: 300px;
border-radius: 50%;
position: relative;
background: #f0f0f0;
transition: transform 5s cubic-bezier(0.17, 0.67, 0.21, 0.99);
}
.wheel-item {
position: absolute;
width: 50%;
height: 50%;
transform-origin: 100% 100%;
text-align: center;
line-height: 150px;
font-size: 14px;
color: #fff;
}
button {
margin-top: 20px;
padding: 10px 20px;
background: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
button:disabled {
background: #cccccc;
cursor: not-allowed;
}
</style>
实现抽奖逻辑
在 methods 中添加 startLottery 方法,用于触发抽奖动画和结果判定:
methods: {
startLottery() {
if (this.isRotating) return;
this.isRotating = true;
const randomPrizeIndex = Math.floor(Math.random() * this.prizes.length);
this.currentPrize = this.prizes[randomPrizeIndex];
const fullRotations = 5; // 完整旋转圈数
const targetAngle = 360 * fullRotations + (360 - (360 / this.prizes.length) * randomPrizeIndex);
this.rotation += targetAngle;
setTimeout(() => {
this.isRotating = false;
alert(`恭喜获得:${this.currentPrize.name}`);
}, 5000); // 与 CSS 过渡时间一致
},
},
优化与扩展
- 奖品概率控制:修改
randomPrizeIndex生成逻辑,实现不同奖品的中奖概率控制。 - 动画效果:调整
cubic-bezier函数或过渡时间,优化旋转动画的流畅度。 - 后端集成:通过
axios调用后端 API,动态获取奖品数据或提交中奖结果。
注意事项
- 确保转盘的初始位置与奖品分布对应,避免视觉偏差。
- 在移动端使用时,考虑添加触摸事件支持。
- 测试不同浏览器下的兼容性,必要时添加前缀或替代方案。







