星星從頁面中心或滑鼠位置向四周飛散,大小、顏色、速度隨機,形成夢幻飛星效果。原文代碼僅提供 CSS 定義與部分 JS 框架,核心動畫邏輯缺失,本文補全並提供現代重構版。

<style>
.star { position:absolute; width:2px; height:2px; background:white; border-radius:50%; pointer-events:none; }
</style>
<script>
// 缺失核心:星星生成、軌跡計算、生命週期管理
// 推測邏輯:setInterval 產生星星 → 隨機角度/速度 → 位移更新 → 超出視窗移除
</script>
const canvas = document.getElementById('stars');
const ctx = canvas.getContext('2d');
const stars = [];
const colors = ['#fff', '#ff0', '#f0f', '#0ff', '#f80'];
function spawnStar(x, y) {
const angle = Math.random() * Math.PI * 2;
const speed = Math.random() * 3 + 1;
stars.push({
x, y,
vx: Math.cos(angle) * speed,
vy: Math.sin(angle) * speed,
size: Math.random() * 2 + 1,
color: colors[Math.floor(Math.random()*colors.length)],
life: 100
});
}
function animate() {
ctx.fillStyle = 'rgba(0,0,0,0.15)'; // 拖尾
ctx.fillRect(0,0,w,h);
stars.forEach((s,i) => {
ctx.beginPath();
ctx.arc(s.x, s.y, s.size, 0, Math.PI*2);
ctx.fillStyle = s.color;
ctx.fill();
s.x += s.vx; s.y += s.vy;
s.life--;
if (s.life <= 0 || s.x < 0 || s.x > w || s.y < 0 || s.y > h) stars.splice(i,1);
});
// 隨機產生新星星
if (Math.random() < 0.3) spawnStar(w/2, h/2);
requestAnimationFrame(animate);
}
animate();
// 滑鼠互動
canvas.addEventListener('mousemove', e => {
if (Math.random() < 0.5) spawnStar(e.clientX, e.clientY);
});
.star {
position: fixed; width: 4px; height: 4px; background: #fff; border-radius: 50%;
animation: fly 2s ease-out forwards; pointer-events: none;
}
@keyframes fly {
from { transform: translate(0,0) scale(1); opacity: 1; }
to { transform: translate(var(--tx), var(--ty)) scale(0); opacity: 0; }
}
// JS 僅需建立元素、設定 --tx/--ty、append、動畫結束 remove()