用Vue.js制作的大转盘

用Vue.js制作的大转盘
最新回答
杰瑞老大

2020-05-05 06:51:25

使用Vue.js制作大转盘的核心步骤如下:

一、基础结构搭建
  1. 创建Vue组件

    <template> <div class="turntable-container"> <div class="wheel" :style="{transform: `rotate(${currentRotate}deg)`}"> <div v-for="(item, index) in prizeList" :key="index" class="sector" :style="getSectorStyle(index)"> {{item.name}} </div> </div> <button @click="startRotate">开始抽奖</button> </div></template>
  2. 数据定义

    data() { return { prizeList: [ {name: "一等奖", probability: 10}, {name: "二等奖", probability: 20}, // ...其他奖项 ], currentRotate: 0, isRotating: false }}
二、核心功能实现
  1. 转盘样式计算

    methods: { getSectorStyle(index) { const count = this.prizeList.length const angle = 360 / count return { transform: `rotate(${angle * index}deg)`, clipPath: `polygon(50% 50%, 50% 0, ${50 + 100 * Math.cos((angle * index) * Math.PI / 180)}% ${50 + 100 * Math.sin((angle * index) * Math.PI / 180)}%)` } }}
  2. 旋转动画控制

    methods: { startRotate() { if (this.isRotating) return this.isRotating = true // 计算目标奖项 const random = Math.random() * 100 let probabilitySum = 0 const targetIndex = this.prizeList.findIndex(item => { probabilitySum += item.probability return random <= probabilitySum }) // 计算旋转角度(基础5圈+目标角度) const baseRotate = 1800 const targetAngle = 360 / this.prizeList.length * targetIndex this.currentRotate = baseRotate + targetAngle // 添加回弹效果 setTimeout(() => { this.currentRotate += 15 // 回弹角度 setTimeout(() => { this.currentRotate -= 15 this.isRotating = false }, 300) }, baseRotate / 360 * 1000) }}
三、高级功能扩展
  1. 拖拽排序功能

    // 安装vuedraggable后import draggable from 'vuedraggable'components: { draggable },<draggable v-model="prizeList" handle=".handle"> <div v-for="(item, index) in prizeList" :key="index"> <span class="handle">≡</span> <input v-model="item.name"> <input v-model.number="item.probability" type="number"> </div></draggable>
  2. 配置保存功能

    methods: { saveConfig() { localStorage.setItem('turntableConfig', JSON.stringify({ prizes: this.prizeList, settings: {/* 其他设置 */} })) }, loadConfig() { const config = JSON.parse(localStorage.getItem('turntableConfig')) if (config) { this.prizeList = config.prizes // 恢复其他设置 } }}
四、样式优化建议.wheel { width: 300px; height: 300px; border-radius: 50%; position: relative; transition: transform 3s cubic-bezier(0.17, 0.67, 0.21, 0.99);}.sector { position: absolute; width: 50%; height: 50%; transform-origin: 100% 100%; left: 0; top: 0; display: flex; align-items: center; justify-content: center;}五、完整实现要点
  1. 概率计算:确保所有奖项概率总和为100,使用累加比较法确定中奖项
  2. 动画控制

    使用CSS transform实现高性能旋转

    通过transition的cubic-bezier实现缓动效果

    添加回弹动画增强体验

  3. 响应式设计:computed: { wheelSize() { return Math.min(window.innerWidth * 0.8, 500) }}
六、DEMO效果参考

完整实现可参考:

Vue-TurnTable DEMO

这个实现包含了:

  • 可视化奖项配置
  • 拖拽排序功能
  • 概率权重计算
  • 平滑旋转动画
  • 配置保存/加载
  • 响应式布局

通过Vue的响应式特性,所有配置变更都会实时反映在转盘上,适合作为营销活动或抽奖游戏的组件使用。