import { getItems, spinWheel } from './api.js'; const canvas = document.getElementById('wheel'); const ctx = canvas.getContext('2d'); const btn = document.getElementById('spin-btn'); const result = document.getElementById('result'); const colors = ['#e74c3c','#3498db','#2ecc71','#f39c12','#9b59b6','#1abc9c']; let items = []; let angle = 0; let spinning = false; async function init() { items = await getItems(); drawWheel(angle); } function drawWheel(rotation) { if (items.length === 0) return; const cx = canvas.width / 2; const cy = canvas.height / 2; const r = cx - 10; const slice = (2 * Math.PI) / items.length; ctx.clearRect(0, 0, canvas.width, canvas.height); items.forEach((item, i) => { const start = rotation + i * slice; const end = start + slice; ctx.beginPath(); ctx.moveTo(cx, cy); ctx.arc(cx, cy, r, start, end); ctx.fillStyle = colors[i % colors.length]; ctx.fill(); ctx.stroke(); ctx.save(); ctx.translate(cx, cy); ctx.rotate(start + slice / 2); ctx.textAlign = 'right'; ctx.fillStyle = '#fff'; ctx.font = 'bold 16px Tahoma'; ctx.fillText(item.title, r - 10, 5); ctx.restore(); }); } btn.onclick = async () => { if (spinning || items.length === 0) return; spinning = true; btn.disabled = true; result.textContent = ''; const data = await spinWheel(); const winner = data.winner; const winnerIdx = items.findIndex(i => i.id === winner.id); const slice = (2 * Math.PI) / items.length; const targetAngle = angle + (Math.PI * 2 * 5) + (Math.PI * 2 - (winnerIdx * slice + slice / 2)); const duration = 4000; const start = performance.now(); const from = angle; function animate(now) { const elapsed = now - start; const t = Math.min(elapsed / duration, 1); const ease = 1 - Math.pow(1 - t, 3); angle = from + (targetAngle - from) * ease; drawWheel(angle); if (t < 1) { requestAnimationFrame(animate); } else { spinning = false; btn.disabled = false; result.textContent = `🎉 ${winner.title}`; } } requestAnimationFrame(animate); }; init();