js实现大转盘抽奖(vue举例)

在开发项目得时候遇到这样一个需求,在移动端项目有个支付抽奖页面,大概效果图如下:

简单介绍一下需求,点击抽奖按钮转盘转动,转盘里边黄色块块是个整张背景图,里边的商品是从接口获取得,包括奖品名称和图片,商品和中奖概率后台可以动态修改,唯一确定得是永远有8个奖品。

1、布局样式

 

每个item对应一个奖项区域,最开始让八个div都在一起,然后按照小红点得位置旋转对应得角度,完成布局。

      .item:nth-child(1) {
        transform: rotate(22deg);
        transform-origin: bottom center;
      }

 

2、概率设置

function chance() {
    // 生成0-1的随机数
    var rand = Math.random();
    // num代表第几个奖品
    var num = 0;
    // 各个奖品的概率
    var probability = [0.1, 0.1, 0.1, 0.1, 0.2, 0.1, 0.1, 0.2];
    if (rand < 0.1) num = 1;
    else if (rand < 0.2) num = 2;
    else if (rand < 0.3) num = 3;
    else if (rand < 0.4) num = 4;
    else if (rand < 0.6) num = 5;
    else if (rand < 0.7) num = 6;
    else if (rand < 0.8) num = 7;
    else if (rand < 1) num = 8;
    return num
}

抽奖的实现有两种思路,点击开始抽奖按钮,率先计算出中了哪个奖品,根据奖品的索引去旋转对应的角度;还有一个思路是随机旋转某个角度,最后根据旋转的角度找到对应奖品。目前使用的是第一中思路,感觉比第二种好算而且好理解。

点击开始抽奖按钮,计算出种了哪个奖品,一种实现是前端自己生成,如上边代码,一种是点击的时候向后端发个请求,后端去计算,然后返回中奖奖品的信息,前端根据信息找到对应的奖品,然后旋转。

3、旋转

function  ratating(deg) {
      // timer计时器
      var timer = null
      // 盛放奖品的里边转盘div
      let inBox = this.$refs['in']
      let _this = this
      // rdm初始的角度,默认1800,旋转5圈,deg是对应奖品的角度(转盘旋转完5圈后再次转多少°能转到对应的奖品),diff是如果连续可以抽多次,那么抽完一次后转盘指针距离一个整圈还差多少度,第二次点击抽奖让指针不用重置,从当前位置继续旋转,第一次旋转初始值为0
      this.rdm = this.rdm + deg + this.diff
      clearInterval(timer)
      // 旋转时长,这里倒计时的时长和css设置的时长对应(transition: all 4s;)
      timer = setInterval(function () {
        inBox.style.transform = "rotate(" + _this.rdm + "deg)"
        clearInterval(timer)
        setTimeout(function () {
          if (_this.info.luck_num > 0) {
            _this.diff = 360 - deg
            _this.rdm += 1800
          }
          // 控制抽奖按钮是否可以点击,转盘旋转结束后可以再次点击
          _this.offOn = !_this.offOn
          // 打开弹框
          _this.mask = true
          _this.stopScroll()
        }, 4000)
      }, 20)
    },              

 

posted @ 2020-12-03 14:38  朝思暮想的虫  阅读(7263)  评论(0编辑  收藏  举报