vue實現九宮格抽獎動畫效果
阿新 • • 發佈:2021-11-25
vue實現九宮格抽獎動畫效果
html佈局九宮格程式碼:
<div class="draw_box"> <div class="item sprite-bg" v-for="(draw, index) in drawPrizes" :class="['item' + index, { active: draw.sort == current }]" :key="index" > <img class="gift-img" :src="draw.giftImg" @error.once="errorImage($event)" /> <div class="name C5-draw">{{ draw.giftName }}</div> </div> <div class="start sprite-bg" @click="start"></div> </div>
css樣式程式碼
.draw_box { position: absolute; top: pxrem(375); left: pxrem(90); width: pxrem(577); height: pxrem(528); .start { position: absolute; width: pxrem(185); height: pxrem(172); background-size: pxrem(750); background-position: pxrem(-189) pxrem(-462); margin-top: pxrem(2); } .item { position: absolute; width: pxrem(185); height: pxrem(172); @extend .flex, .flex-align-center, .flex-v, .flex-pack-center; background-size: pxrem(750); background-position: pxrem(0) pxrem(-462); .gift-img { display: block; width: pxrem(110); height: pxrem(110); } .name { font-size: pxrem(26); margin-top: pxrem(5); } } .item0, .item1, .item2 { top: pxrem(0); } .item4, .item5, .item6 { bottom: pxrem(0); } .item3, .item7, .start { top: pxrem(178); } .item0, .item7, .item6 { left: pxrem(0); } .item2, .item3, .item4 { right: pxrem(5); } .item1, .item5, .start { left: pxrem(193); } .active { background-size: pxrem(750); background-position: pxrem(0) pxrem(-636); } }
js邏輯執行程式碼
//介面獲取完成抽中哪個獎勵之後執行startRoll方法 //切換九宮格的動畫相關引數 latexBox: { index: 0, // 當前轉動到哪個位置,第一次起點位置0,對應頁面item1位置 times: 0, // 轉動跑格子次數, cycle: 40, // 轉動基本次數:即至少需要轉動多少次再進入抽獎環節 speed: 150, // 初始轉動速度 timer: null, timerPop: null, //抽獎之後停一下在彈出彈窗 prizeIndex: 0, //抽中的獎勵所在位置 }, // 九宮格開始轉動 startRoll() { this.isShowAnimation = true; this.latexBox.times += 1; // 轉動次數 this.oneRoll(); // 轉動過程呼叫的每一次轉動方法,這裡是第一次呼叫初始化 this.showLatexBox(); }, // 九宮格每一次轉動 oneRoll() { let index = this.latexBox.index; // 當前轉動到哪個位置 const count = 8; // 總共有多少個位置 index += 1; if (index > count) { index = 0; } this.latexBox.index = index; }, //九宮格動畫 showLatexBox() { // 如果當前轉動次數達到要求 && 目前轉到的位置是中獎位置 if ( this.latexBox.times > this.latexBox.cycle && this.latexBox.prizeIndex === this.latexBox.index ) { clearTimeout(this.latexBox.timer); // 清除轉動定時器 this.latexBox.timerPop = setTimeout(() => { this.transformEndEvent(); }, 500); this.latexBox.speed = 150; this.latexBox.times = 0; // 轉動跑格子次數初始化為0,可以開始下次抽獎 } else { if (this.latexBox.times < this.latexBox.cycle - 20) { this.latexBox.speed -= 5; // 加快轉動速度 } else { this.latexBox.speed += 15; // 抽獎即將結束,放慢轉動速度 } this.latexBox.timer = setTimeout( this.startRoll, this.latexBox.speed ); //開始轉動 } },
總體邏輯就是,每隔多少秒轉動一次格子,然後根距初始設定的轉動次數,中途加快和放慢轉速,最後符合次數之後,轉到中獎位置,停頓一下彈出獎品。