大轉盤抽獎是營銷活動常見需求。本文從零構建一個完整轉盤組件:Canvas 高效能繪製、CSS3/JS 動畫緩動、服務端驗證概率、防作弊機制,附完整代碼架構。
class LuckyWheel {
constructor(canvasId, options = {}) {
this.canvas = document.getElementById(canvasId);
this.ctx = this.canvas.getContext('2d');
this.segments = options.segments || 8; // 扇區數
this.prizes = options.prizes || []; // 獎品配置 [{text, color, probability, ...}]
this.colors = options.colors || this.defaultColors();
this.font = options.font || '16px Microsoft YaHei';
this.radius = Math.min(this.canvas.width, this.canvas.height) / 2 - 10;
this.centerX = this.canvas.width / 2;
this.centerY = this.canvas.height / 2;
this.angle = 0; // 當前旋轉角度
this.isSpinning = false;
this.draw();
}
defaultColors() {
return ['#FF6B6B', '#4ECDC4', '#45B7D1', '#FFBE0B', '#FB5607', '#8338EC', '#3A86FF', '#06D6A0'];
}
}
draw() {
const ctx = this.ctx;
ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
ctx.save();
ctx.translate(this.centerX, this.centerY);
ctx.rotate(this.angle);
const sliceAngle = (2 * Math.PI) / this.segments;
for (let i = 0; i < this.segments; i++) {
const startAngle = i * sliceAngle;
const endAngle = startAngle + sliceAngle;
// 扇區背景
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.arc(0, 0, this.radius, startAngle, endAngle);
ctx.closePath();
ctx.fillStyle = this.colors[i % this.colors.length];
ctx.fill();
ctx.strokeStyle = '#fff';
ctx.lineWidth = 2;
ctx.stroke();
// 獎品文字
ctx.save();
ctx.rotate(startAngle + sliceAngle / 2);
ctx.textAlign = 'right';
ctx.fillStyle = '#fff';
ctx.font = this.font;
const prize = this.prizes[i] || {text: `獎項 ${i+1}`};
ctx.fillText(prize.text, this.radius - 10, 5);
ctx.restore();
}
// 中心圓
ctx.beginPath();
ctx.arc(0, 0, 30, 0, 2 * Math.PI);
ctx.fillStyle = '#fff';
ctx.fill();
ctx.fillStyle = '#333';
ctx.font = 'bold 14px Microsoft YaHei';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText('開始', 0, 0);
ctx.restore();
}
spin(targetSegmentIndex, onComplete) {
if (this.isSpinning) return;
this.isSpinning = true;
// 目標角度:指針指向目標扇區中心
const sliceAngle = (2 * Math.PI) / this.segments;
const targetAngle = - (targetSegmentIndex * sliceAngle + sliceAngle / 2) + Math.PI / 2; // 指針朝上
// 總圈數:至少 5 圈 + 目標角度
const totalRounds = 5 + Math.random() * 2; // 5-7 圈隨機
const targetTotalAngle = totalRounds * 2 * Math.PI + targetAngle;
const startAngle = this.angle;
const duration = 4000; // 4 秒
const startTime = performance.now();
const animate = (now) => {
const elapsed = now - startTime;
const progress = Math.min(elapsed / duration, 1);
// 緩動函數:easeOutCubic
const eased = 1 - Math.pow(1 - progress, 3);
this.angle = startAngle + (targetTotalAngle - startAngle) * eased;
this.draw();
if (progress < 1) {
requestAnimationFrame(animate);
} else {
this.isSpinning = false;
this.angle = targetTotalAngle % (2 * Math.PI);
this.draw();
onComplete?.(this.prizes[targetSegmentIndex]);
}
};
requestAnimationFrame(animate);
}
前端僅負責表現,中獎邏輯必須在後端決定。
// 後端 API 範例
app.post('/api/lottery/spin', (req, res) => {
const userId = req.user.id;
// 1. 檢查抽獎次數限制
// 2. 根據配置概率抽獎
const prizes = [
{id: 1, name: '一等獎', prob: 0.001},
{id: 2, name: '二等獎', prob: 0.01},
{id: 3, name: '三等獎', prob: 0.05},
{id: 4, name: '參與獎', prob: 0.939}
];
const rand = Math.random();
let acc = 0;
let won = null;
for (const p of prizes) {
acc += p.prob;
if (rand < acc) { won = p; break; }
}
// 3. 記錄中獎記錄
// 4. 返回前端需旋轉到的扇區索引
const segmentIndex = prizes.findIndex(p => p.id === won.id);
res.json({success: true, prize: won, segmentIndex});
});
const wheel = new LuckyWheel('wheelCanvas', {
segments: 8,
prizes: [
{text: '一等獎', color: '#FF6B6B'},
{text: '二等獎', color: '#4ECDC4'},
{text: '三等獎', color: '#45B7D1'},
{text: '參與獎', color: '#FFBE0B'},
{text: '參與獎', color: '#FB5607'},
{text: '參與獎', color: '#8338EC'},
{text: '參與獎', color: '#3A86FF'},
{text: '參與獎', color: '#06D6A0'}
]
});
document.getElementById('spinBtn').addEventListener('click', async () => {
if (wheel.isSpinning) return;
try {
const res = await fetch('/api/lottery/spin', {method: 'POST', credentials: 'include'});
const {success, prize, segmentIndex} = await res.json();
if (success) {
wheel.spin(segmentIndex, (prize) => {
showModal(`恭喜獲得:${prize.text}`);
});
} else {
alert('抽獎失敗:' + res.message);
}
} catch (err) {
alert('網路錯誤');
}
});
大轉盤抽獎核心在於:Canvas 高效繪製 + requestAnimationFrame 緩動動畫 + 後端權威概率控制 + 前端表現與邏輯分離。掌握這套架構,可快速構建穩定、公平、可擴展的抽獎系統,並輕鬆適配各種營銷活動場景。