萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

HTML 星星從背景飛出特效代碼解析與 Canvas 重構

效果描述

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

原始碼片段補全

<style>
.star { position:absolute; width:2px; height:2px; background:white; border-radius:50%; pointer-events:none; }
</style>
<script>
// 缺失核心:星星生成、軌跡計算、生命週期管理
// 推測邏輯:setInterval 產生星星 → 隨機角度/速度 → 位移更新 → 超出視窗移除
</script>

完整 Canvas 實現 (推薦生產使用)

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);
});

CSS 純樣式替代方案 (極簡版)

.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()

適用場景

  • 節日專題頁 (聖誕、新年、七夕)
  • 遊戲/活動頁背景裝飾
  • 載入等待、轉場動畫點綴
copyright © 萬盛學電腦網 all rights reserved