萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 實現轉盤抽獎/隨機數轉動特效完整教學

前言

轉盤抽獎、幸運大轉盤、跑馬燈式隨機數選擇是行銷活動、年會抽獎、電商促銷的高頻需求。本文從零構建一個功能完整、動畫流暢、可控中獎概率、支援自定義獎品的 jQuery 轉盤抽獎元件。

核心動畫原理

  • 狀態機:待機 → 加速 → 匀速 → 減速 → 停止於目標
  • 時間控制:setInterval 逐幀切換高亮項目,動態調整間隔實現變速
  • 視覺回饋:CSS 高亮類別 + 可選 CSS 動畫 (脈衝、縮放)

HTML 結構


<div class="lottery-wheel" id="lottery-wheel">
    <ul class="wheel-items">
        <li data-index="1" data-prize="特獎:iPhone 15 Pro"><span>特獎</span></li>
        <li data-index="2" data-prize="一獎:AirPods Pro"><span>一獎</span></li>
        <li data-index="3" data-prize="二獎:購物金 500 元"><span>二獎</span></li>
        <li data-index="4" data-prize="三獎:折價券 100 元"><span>三獎</span></li>
        <li data-index="5" data-prize="四獎:精美禮品"><span>四獎</span></li>
        <li data-index="6" data-prize="五獎:感謝參加"><span>五獎</span></li>
        <li data-index="7" data-prize="六獎:再接再厲"><span>六獎</span></li>
        <li data-index="8" data-prize="特獎:iPhone 15 Pro"><span>特獎</span></li>
        <li data-index="9" data-prize="一獎:AirPods Pro"><span>一獎</span></li>
        <li data-index="10" data-prize="二獎:購物金 500 元"><span>二獎</span></li>
        <li data-index="11" data-prize="三獎:折價券 100 元"><span>三獎</span></li>
        <li data-index="12" data-prize="四獎:精美禮品"><span>四獎</span></li>
        <li data-index="13" data-prize="五獎:感謝參加"><span>五獎</span></li>
        <li data-index="14" data-prize="六獎:再接再厲"><span>六獎</span></li>
    </ul>
    <button type="button" class="lottery-trigger" id="start-btn">開始抽獎</button>
    <div class="lottery-result" id="result" hidden></div>
</div>

CSS 樣式 (關鍵:環狀排版與高亮動畫)


.lottery-wheel {
    position: relative;
    width: 400px; height: 400px;
    margin: 40px auto;
    border-radius: 50%;
    background: conic-gradient(from 0deg, #ff6b6b, #feca57, #48dbfb, #ff9ff3, #54a0ff, #5f27cd);
    padding: 8px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.2);
}

.wheel-items {
    position: relative;
    width: 100%; height: 100%;
    border-radius: 50%;
    background: white;
    list-style: none;
    margin: 0; padding: 0;
    transform: rotate(-11.25deg); // 修正首項對齊 (360/14/2)
}

.wheel-items li {
    position: absolute;
    top: 50%; left: 50%;
    width: 120px; height: 60px;
    margin: -30px 0 0 -60px; // 中心對齊
    transform-origin: 60px 200px; // 旋轉中心 = 輪盤中心
    text-align: center;
    line-height: 60px;
    font-weight: bold;
    color: #333;
    border: 2px solid transparent;
    border-radius: 8px;
    transition: all 0.2s ease;
    cursor: default;
}

.wheel-items li.current {
    background: #fffbe6;
    border-color: #ffd700;
    box-shadow: 0 0 15px rgba(255,215,0,0.6), inset 0 0 20px rgba(255,215,0,0.2);
    transform: scale(1.1);
    z-index: 10;
    animation: pulse 0.5s ease-in-out infinite alternate;
}

@keyframes pulse {
    from { box-shadow: 0 0 15px rgba(255,215,0,0.6); }
    to { box-shadow: 0 0 25px rgba(255,215,0,1), inset 0 0 30px rgba(255,215,0,0.3); }
}

.lottery-trigger {
    position: absolute;
    top: 50%; left: 50%;
    transform: translate(-50%, -50%);
    width: 120px; height: 120px;
    border-radius: 50%;
    background: linear-gradient(135deg, #ff6b6b, #ee5a5a);
    color: white;
    font-size: 18px;
    font-weight: bold;
    border: none;
    cursor: pointer;
    box-shadow: 0 5px 20px rgba(255,107,107,0.5);
    transition: transform 0.2s, box-shadow 0.2s;
    z-index: 20;
}
.lottery-trigger:hover { transform: translate(-50%, -50%) scale(1.05); box-shadow: 0 8px 30px rgba(255,107,107,0.7); }
.lottery-trigger:disabled { opacity: 0.6; cursor: not-allowed; transform: translate(-50%, -50%); }

.lottery-result {
    margin-top: 20px;
    padding: 20px;
    background: #fffbe6;
    border: 2px solid #ffd700;
    border-radius: 8px;
    text-align: center;
    font-size: 18px;
    animation: fadeIn 0.5s ease;
}
@keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }

核心 jQuery 邏輯 (狀態機實現)


;(function($) {
    $.fn.lotteryWheel = function(options) {
        const settings = $.extend({
            items: '.wheel-items li',      // 獎項選擇器
            trigger: '.lottery-trigger',   // 觸發按鈕
            result: '.lottery-result',     // 結果顯示區
            speed: 50,                     // 初始速度 (ms)
            accelerationSteps: 5,          // 加速步數
            maxSpeed: 30,                  // 最高速度 (ms, 數值越小越快)
            constantRounds: 3,             // 匀速圈數
            decelerationStart: 5,          // 目標前幾格開始減速
            minDecelSpeed: 300,            // 最低速度 (ms)
            onStart: null,                 // 開始回呼
            onEnd: null                    // 結束回呼: function(prizeData)
        }, options);

        return this.each(function() {
            const $wheel = $(this);
            const $items = $wheel.find(settings.items);
            const $trigger = $wheel.find(settings.trigger);
            const $result = $wheel.find(settings.result);
            
            const totalItems = $items.length;
            let currentIndex = 0;
            let timer = null;
            let state = 'idle'; // idle, accelerating, constant, decelerating, stopping
            let cycleCount = 0;
            let targetIndex = -1;
            let currentSpeed = settings.speed;
            let accelStep = 0;

            // 計算目標索引 (可傳入指定索引或隨機)
            function determineTarget(customIndex) {
                if (typeof customIndex === 'number' && customIndex >= 0 && customIndex < totalItems) {
                    return customIndex;
                }
                // 預設隨機 (可替換為加權隨機演算法)
                return Math.floor(Math.random() * totalItems);
            }

            // 狀態機:下一幀
            function tick() {
                switch (state) {
                    case 'accelerating':
                        accelerate();
                        break;
                    case 'constant':
                        constantSpeed();
                        break;
                    case 'decelerating':
                        decelerate();
                        break;
                    case 'stopping':
                        checkStop();
                        break;
                }
            }

            function accelerate() {
                highlightNext();
                accelStep++;
                if (accelStep >= settings.accelerationSteps) {
                    state = 'constant';
                    cycleCount = 0;
                    currentSpeed = settings.maxSpeed;
                } else {
                    // 逐步加速 (指數級)
                    currentSpeed = Math.max(settings.maxSpeed, currentSpeed * 0.8);
                }
                resetTimer();
            }

            function constantSpeed() {
                highlightNext();
                cycleCount += 1 / totalItems; // 圈數累積
                if (cycleCount >= settings.constantRounds) {
                    state = 'decelerating';
                }
                resetTimer();
            }

            function decelerate() {
                highlightNext();
                
                // 檢查是否進入減速區 (目標前 N 格)
                const distanceToTarget = (targetIndex - currentIndex + totalItems) % totalItems;
                if (distanceToTarget <= settings.decelerationStart) {
                    state = 'stopping';
                } else {
                    // 逐步減速 (線性或指數)
                    currentSpeed = Math.min(settings.minDecelSpeed, currentSpeed * 1.15);
                }
                resetTimer();
            }

            function checkStop() {
                highlightNext();
                if (currentIndex === targetIndex) {
                    // 到達目標,最後緩慢確認
                    currentSpeed = Math.min(settings.minDecelSpeed, currentSpeed * 1.2);
                    if (currentSpeed >= settings.minDecelSpeed * 0.95) {
                        stopWheel();
                    }
                } else {
                    currentSpeed = Math.min(settings.minDecelSpeed, currentSpeed * 1.1);
                }
                resetTimer();
            }

            function highlightNext() {
                $items.removeClass('current');
                currentIndex = (currentIndex + 1) % totalItems;
                $items.eq(currentIndex).addClass('current');
            }

            function resetTimer() {
                clearTimeout(timer);
                timer = setTimeout(tick, currentSpeed);
            }

            function stopWheel() {
                clearTimeout(timer);
                state = 'idle';
                $trigger.prop('disabled', false).text('開始抽獎');
                
                const prizeData = $items.eq(targetIndex).data();
                $result.html(`🎉 恭喜獲得:${prizeData.prize}`).show();
                
                if ($.isFunction(settings.onEnd)) {
                    settings.onEnd(prizeData, targetIndex);
                }
            }

            // 開始抽獎
            $trigger.on('click', function() {
                if (state !== 'idle') return;
                
                $trigger.prop('disabled', true).text('抽獎中...');
                $result.hide();
                
                // 重置狀態
                $items.removeClass('current');
                currentIndex = 0;
                $items.eq(0).addClass('current');
                
                targetIndex = determineTarget();
                state = 'accelerating';
                currentSpeed = settings.speed;
                accelStep = 0;
                cycleCount = 0;
                
                if ($.isFunction(settings.onStart)) settings.onStart();
                
                tick();
            });

            // 公開 API
            $wheel.data('lotteryWheel', {
                start: (customIndex) => {
                    if (state === 'idle') {
                        targetIndex = determineTarget(customIndex);
                        $trigger.click();
                    }
                },
                getState: () => state,
                getCurrentPrize: () => $items.eq(currentIndex).data()
            });
        });
    };
})(jQuery);

初始化與進階控制


$(function() {
    $('#lottery-wheel').lotteryWheel({
        speed: 80,
        maxSpeed: 20,
        constantRounds: 4,
        decelerationStart: 6,
        minDecelSpeed: 400,
        onStart: () => console.log('抽獎開始'),
        onEnd: (prize, index) => {
            console.log('中獎:', prize.prize, '索引:', index);
            // AJAX 送往後端記錄中獎紀錄
            $.post('/api/lottery/record', { prizeId: prize.index, prizeName: prize.prize });
        }
    });

    // 後端決定中獎結果 (防作弊架構)
    $('#start-btn').on('click', function() {
        const $btn = $(this);
        const $wheel = $('#lottery-wheel');
        
        // 1. 先請求後端抽獎結果
        $.post('/api/lottery/draw', { activityId: 123 })
            .done(res => {
                if (res.success && res.data.prizeIndex !== undefined) {
                    // 2. 觸發轉盤並指定停止位置
                    $wheel.data('lotteryWheel').start(res.data.prizeIndex);
                } else {
                    alert(res.message || '抽獎失敗');
                    $btn.prop('disabled', false).text('開始抽獎');
                }
            })
            .fail(() => {
                alert('網路錯誤,請重試');
                $btn.prop('disabled', false).text('開始抽獎');
            });
        
        return false; // 阻止預設觸發
    });
});

加權隨機演算法 (後端/前端通用)


function weightedRandom(prizes) {
    // prizes: [{ id, name, weight, ... }, ...] weight 為權重 (數值越大機率越高)
    const totalWeight = prizes.reduce((sum, p) => sum + (p.weight || 1), 0);
    let random = Math.random() * totalWeight;
    
    for (const prize of prizes) {
        random -= (prize.weight || 1);
        if (random <= 0) return prize;
    }
    return prizes[0]; // fallback
}

// 獎品配置範例
const prizesConfig = [
    { index: 0, name: '特獎', prize: 'iPhone 15', weight: 1 },
    { index: 1, name: '一獎', prize: 'AirPods', weight: 2 },
    { index: 2, name: '二獎', prize: '500元', weight: 5 },
    { index: 3, name: '三獎', prize: '100元', weight: 10 },
    { index: 4, name: '四獎', prize: '禮品', weight: 20 },
    { index: 5, name: '五獎', prize: '謝謝參加', weight: 50 },
    // ... 對應 14 格位置重複排列
];

CSS 3D 立體轉盤進階版 (可選)

使用 CSS 3D Transform 實現真正的立體轉盤旋轉 (而非高亮切換):


.wheel-3d {
    width: 300px; height: 300px;
    transform-style: preserve-3d;
    transform: rotateX(-20deg); // 俯視角度
    animation: spin 4s cubic-bezier(0.17, 0.67, 0.12, 0.99) forwards;
}

.wheel-3d .slice {
    position: absolute;
    width: 100%; height: 100%;
    transform-origin: 50% 50% -150px; // 圓心在 Z 軸負方向
    clip-path: polygon(50% 50%, 100% 0, 100% 100%); // 扇形裁切
    backface-visibility: hidden;
}

// JS 動態計算每片旋轉角度並套用
const angle = 360 / slices.length;
slices.forEach((slice, i) => {
    slice.style.transform = `rotateZ(${i * angle}deg) translateZ(0)`;
});

// 停止角度計算
const targetDeg = 360 * 5 + (360 - targetIndex * angle) + angle/2; // 多轉 5 圈 + 目標角度
wheel.style.animation = `spin ${duration}s cubic-bezier(...) forwards`;
wheel.style.setProperty('--target-deg', `${targetDeg}deg`);

// CSS
@keyframes spin { to { transform: rotateX(-20deg) rotateZ(var(--target-deg)); } }

總結

轉盤抽獎核心在於 狀態機控制速度曲線 (加速→匀速→減速→停止) 與 前後端分離防作弊 (後端決定結果,前端只負責演示)。jQuery 實作靈活易懂,封裝為 Plugin 可複用。現代專案若需 3D 真實旋轉效果,建議改用 CSS 3D Transform + `animation` 配合 JS 計算目標角度,效能更佳、視覺更真實。

copyright © 萬盛學電腦網 all rights reserved