[兔了个兔]——兔年抽奖轮盘

190 阅读2分钟

我正在参加「兔了个兔」创意投稿大赛,详情请看:「兔了个兔」创意投稿大赛

新年很多公司都开起了年会,年会上少不了抽奖环节,对于公司没有年会的我来说,只有狠狠地羡慕了,只能自己动手做一个抽奖轮盘安慰下自己。

实现

抽奖轮盘分为三部分:大轮盘,小轮盘,指针,当我们点击指针的时候,小轮盘转动,停下来指针指到的区域就是奖品啦。

  • 大轮盘。利用css中border-radius属性画出一个圆形,添加我们喜欢的背景色,边框颜色:
     .big-circle {
        width: 230px;
        height: 230px;
        border-radius: 230px;
        border: 5px solid #e84413;
        background: #bc1704;
        opacity: 0.8;
        display: flex;
        justify-content: center;
        align-items: center;
        position: relative;
      }
  • 指针。我们找到一个指针图片,通过content属性展示出来,再利用position定位到大轮盘中心:
   .pointer {
        width: 50px;
        height: 50px;
        border-radius: 45px;
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%);
        position: absolute;
        content: url(./images/pointer.png) no-repeat;
      }
  • 小轮盘。小轮盘就是我们奖品展示轮盘,它是由四个扇形拼接起来的,我们借用border属性达到这一效果。首先我们将宽高设为0,border设置成我们想要的大小,通过border-color给四个边框设置出我们想要的颜色,最后将边框变为圆形。
    .small-circle {
        width: 0;
        height: 0;
        border-radius: 100%;
        border: 100px solid;
        border-color: #fccb90 #f3660f #fccb90 #f3660f;
        position: relative;
        color: white;
      }

下面就是奖品的展示,依旧通过定位将我们的图片素材放到小轮盘上面,这里有个小细节,左右下的图片我们要通过ratate调整下位置。

   .left {
        position: absolute;
        top: -30px;
        left: -90px;
        transform: rotate(-90deg);
      }
      //其他三个方位调整下top left rotate的值即可

三者组合到一起就能得到抽奖轮盘啦

   <div class="wrapper">
      <div class="big-circle">
        <div class="small-circle">
          <div class="top">
            <img src="./images/purse.png" alt="" />
          </div>
          <div class="right">
            <img src="./images/cry.png" alt="">
          </div>
          <div class="bottom">
            <img src="./images/gift.png" alt="" />
          </div>
          <div class="left">
            <img src="./images/smallRabbit.png" alt="">
          </div>
        </div>
        <div class="pointer"></div>
      </div>
    </div>

布局完成,接下来我们给指针添加点击事件,让小轮盘转起来。利用Math.random()随机得到旋转的角度跟圈数,两者相乘得到总角度,利用dom方法设置小轮盘旋转总角度。

   const pointer = document.getElementsByClassName('pointer')[0];
      const circle = document.getElementsByClassName('small-circle')[0];
      pointer.onclick = () => {
        circle.style.transform = `rotate(0deg)`;
        const deg = Math.floor(Math.random() * 360);
        const count = Math.floor(Math.random() * 6 + 3);
        const rotate = count * 360 + deg;
        circle.style.transform = `rotate(${rotate}deg)`;
        circle.style.transition = '3s';
      };

总结

虽然这个轮盘抽到奖的概率只有75%,总的来说还是挺公平的,如果不小心抽到哭脸,赶紧再点一次。