【javascript】九宮格抽獎組件設計

一些主要點

1. 轉圈的順序(順時針或者逆時針);css

2. 轉圈的速率(從慢到快再到慢);前端

3. 位置的問題(下一次抽獎的起始位置是上一次抽獎的結束位置);css3

4. 轉圈的圈數或者移動的次數。dom

基本原理

1. 抽獎的過程其實就是經過不斷的改變 dom(一般爲 li)的索引值,來達到移動的效果(好比 8 個獎項,索引值的變化以下 0 -> 1, 1 -> 2, ... , 6 -> 7 , 7 -> 0),因此 dom 的排版(絕對定位)就顯得很重要了;函數

2. 對於移動的速度其實就是 dom 切換的快慢,在 js 中,咱們能夠經過定時器 setTimeout 的執行時間來控制移動的速度;動畫

3. 移動速度的增減;this

4. 何時移動結束。spa

如何寫代碼

外部如何使用

1. 首先經過構造函數實例化,而且在實例化時傳入相關參數(通常都爲 object)(好比 var lottery = new Lottery(opts)),來實現該組件的初始化;指針

2. 組件初始化後,還須要有個方法來執行抽獎的過程(好比 lottery.start());code

3. 固然咱們還須要告訴組件中的是什麼獎勵(通常都是接口調用返回給前端),即中獎的位置在哪裏,至關於獎勵的索引(好比 lottery.prize = 1)。

實例化參數 opts

  • opts.index 當前移動到哪一個位置,起點位置,默認第一個(即容器的第一個子元素)
  • opts.length 獎勵個數,默認 8 個
  • opts.speed 初始移動速度
  • opts.maxSpeed 移動最大速度,數值越小,移動越快
  • opts.minSpeed 移動最小速度,數值越大,移動越慢
  • opts.base 基本移動次數,即小於基本轉動次數時,速度遞增,大於該數值,速度遞減
  • opts.totals 總移動次數,即大於該數值時,轉動即將結束
  • opts.moveTo 移動的過程,有兩個參數(before 和 after),before 是移動前的索引值,after 是移動後的索引值,能夠在這個方法中本身設置動畫效果,好比 css3
  • opts.callback 移動結束以後的回調

內部實現

'use strict';
module.exports = function Lottery(opts) {
    this.index = opts.index || 0;
    this.speed = opts.speed || 60;
    this.maxSpeed = opts.maxSpeed || 40;
    this.minSpeed = opts.minSpeed || 250;
    this.base = opts.base || 3;
    this.totals = opts.totals || 12;
    this.length = opts.length || 8;
    this.prize = -1; // 中獎位置,須要外部來更新
    var self = this;
    var speed = self.speed;
    var timer = null; // 定時器 ID
    var counts = 0; // 移動次數計數
    // 在移動的過程當中,其實就是索引值的改變,好比 0 -> 1, 1 -> 2, ... , 6 -> 7 , 7 -> 0
    var move = function() {
        var index = self.index;
        var len = self.length;
        var before = self.index; // 當前
        index += 1; // 下一個
        // 當索引到最後一個時,下一個索引就是第一個
        if (index > len - 1) {
            index = 0;
        }
        opts.moveTo && opts.moveTo(before, index);
        self.index = index;
    };
    // 外部調用抽獎方法
    this.start = function() {
        move();
        counts += 1;
        if (counts > this.totals && this.prize === this.index) {
            clearTimeout(timer);
            counts = 0;
            speed = this.speed;
            this.prize = -1;
            opts.callback && opts.callback();
        } else {
            if (counts < this.base) {
                speed -= 10;
            } else {
                if (counts > this.totals) {
                    speed += 60;
                } else {
                    speed += 30;
                }
            }
            speed = speed < this.maxSpeed ? this.maxSpeed : (speed > this.minSpeed ? this.minSpeed : speed);
            timer = setTimeout(function() {
                self.start();
            }, speed);
        }
    };
};

擴展

1. 不限九宮格排列的抽獎;

2. 能夠知足圓盤式指針旋轉的抽獎。

相關文章
相關標籤/搜索