JS转盘抽奖

前几年在公司因业务需要疯狂的写了一堆小游戏,刚抽空写了一个最简单的转盘抽奖游戏demo,用的JS和CSS3,几句话就搞定。

注意这只是一个简单的demo,转盘游戏在生产坏境中还有很多需要注意的地方,交互体验也有很多细节可以做,有其他功能需要可以留言我会为你解决。

实现思路,通过CSS3的过渡与旋转来实现动画效果,通过JS来触发和控制转盘的动画,效果图是gif看着头晕,我放在最后面了。

完整代码:


<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>gametitle>
  <style>
    * {
       margin: 0; padding: 0; line-height: 1; }
    .box{
       position: relative; width: 802px; height: 802px; overflow: hidden; margin:0 auto; }
    .turntable{
       width: 802px; height: 802px; }
    .btn{
       position: absolute; top: 50%; left: 50%; width: 320px; height: 320px; margin: -160px 0 0 -160px; border-radius: 100%; cursor: pointer; user-select: none; }
    .btn:active {
       transform: scale(0.9); }
  style>
head>
<body>
  <div class="box">
    
    <img id="turntable" src="./images/1.png" class="turntable"/>
    
    <img id="startButton" src="./images/2.png" class="btn"/>
  div>
  <script>
    // 区分是否可以点击按钮开始抽奖
    let isRotate = true
    // 盘子数据
    const data = [
      {
      
        name: '运动',
        rotate: 0,
      },
      {
      
        name: '学习',
        rotate: 90,
      },
      {
      
        name: '休息',
        rotate: 180,
      },
      {
      
        name: '喝奶茶',
        rotate: 270,
      }
    ]
    // 游戏
    const game = {
      
      turntable: null,  // 盘子
      angle: 0, // 旋转角度
      lastAngle: 0, // 上次旋转角度
      transitionTime: 5, // 过渡时间 默认5秒
      init(turntable) {
        // 初始化游戏
        this.turntable = turntable
        this.turntable.style.transition = `all ${
        this.transitionTime}s`
      },
      rotate(angle, callback) {
       // 旋转盘子 angle = 旋转角度 callback = 旋转结束的回调函数
        const defaultAngle = 1800 // 默认先转5圈 再移到正确位置
        this.angle += defaultAngle + angle - this.lastAngle
        this.lastAngle = angle
        this.turntable.style.transform = `rotate(${
        this.angle}deg)`
        setTimeout(() => {
      
          callback()
        },this.transitionTime * 1000)
      }
    }
    // 开始抽奖
    const startGame = () => {
      
      // 控制抽奖频率
      if (!isRotate) {
       return }
      isRotate = false
      // 产生随机数,获得随机抽奖结果
      const num = Math.floor(Math.random() * data.length)
      // 启动
      game.rotate(data[num].rotate, () => {
      
        // 动画结束,展示结果
        alert(`恭喜你喜提-${
        data[num].name}`)
        isRotate = true
      })
    }
    // 页面加载后再执行游戏相关操作
    window.onload = () => {
      
      const turntable = document.getElementById('turntable')
      const startButton = document.getElementById('startButton')
      // 初始化游戏
      game.init(turntable)
      // 绑定开始抽奖按钮点击事件
      startButton.onclick = startGame
    }
  script>
body>
html>

图片素材:
JS转盘抽奖_第1张图片
JS转盘抽奖_第2张图片
最终效果:

你可能感兴趣的:(随记,html,html5,css3,javascript,前端)