萬盛學電腦網

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

原生 JavaScript 實現煙花爆炸特效:Canvas 粒子系統演進版

效果預覽

點擊頁面任意位置,綻放多彩煙花,粒子受重力影響自然下落並逐漸消失。純原生 JS,無依賴,約 80 行核心代碼。

核心原理

  1. 發射階段:從底部發射一條「引線」粒子至點擊位置
  2. 爆炸階段:在目標座標生成 N 個粒子,隨機角度、速度、顏色
  3. 物理模擬:每幀更新位置 x += vx, y += vy,速度受重力 vy += gravity
  4. 生命週期:粒子超出視口或透明度歸零則移除
  5. 渲染循環:requestAnimationFrame 驅動 60fps 動畫

完整可運行代碼(單文件)

<!DOCTYPE html>
<html lang="zh-Hant">
<head>
  <meta charset="UTF-8">
  <title>JS 煙花特效</title>
  <style>
    * { margin:0; padding:0; }
    html, body { width:100%; height:100%; overflow:hidden; background:#000; }
    canvas { display:block; }
  </style>
</head>
<body>
  <canvas id="fireworks"></canvas>
  <script>
(function () {
  var canvas = document.getElementById('fireworks');
  var ctx = canvas.getContext('2d');
  var particles = [];
  var GRAVITY = 0.08;
  var COLORS = ['#ff6b6b', '#feca57', '#48dbfb', '#ff9ff3', '#54a0ff', '#5f27cd', '#00d2d3', '#1dd1a1'];

  // 適配高 DPI
  function resize() {
    var dpr = window.devicePixelRatio || 1;
    canvas.width = window.innerWidth * dpr;
    canvas.height = window.innerHeight * dpr;
    canvas.style.width = window.innerWidth + 'px';
    canvas.style.height = window.innerHeight + 'px';
    ctx.scale(dpr, dpr);
  }
  window.addEventListener('resize', resize);
  resize();

  // 粒子類
  function Particle(x, y, color, angle, speed, size, life) {
    this.x = x;
    this.y = y;
    this.color = color;
    this.vx = Math.cos(angle) * speed;
    this.vy = Math.sin(angle) * speed;
    this.size = size;
    this.life = life;
    this.maxLife = life;
    this.alpha = 1;
  }
  Particle.prototype.update = function () {
    this.x += this.vx;
    this.y += this.vy;
    this.vy += GRAVITY; // 重力
    this.life--;
    this.alpha = this.life / this.maxLife;
  };
  Particle.prototype.draw = function () {
    ctx.globalAlpha = this.alpha;
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
    ctx.fillStyle = this.color;
    ctx.fill();
    ctx.globalAlpha = 1;
  };

  // 發射引線
  function launch(targetX, targetY) {
    var x = targetX;
    var y = window.innerHeight;
    var tracer = {
      x: x, y: y,
      vx: 0, vy: -12, // 向上發射速度
      size: 3,
      color: '#fff',
      alpha: 1
    };

    function animateTracer() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      // 繪製現有粒子
      for (var i = particles.length - 1; i >= 0; i--) {
        var p = particles[i];
        p.update();
        p.draw();
        if (p.life <= 0 || p.y > window.innerHeight + 50) particles.splice(i, 1);
      }
      // 繪製引線
      tracer.y += tracer.vy;
      ctx.globalAlpha = tracer.alpha;
      ctx.beginPath();
      ctx.arc(tracer.x, tracer.y, tracer.size, 0, Math.PI * 2);
      ctx.fillStyle = tracer.color;
      ctx.fill();
      ctx.globalAlpha = 1;

      if (tracer.y <= targetY) {
        explode(targetX, targetY);
      } else {
        requestAnimationFrame(animateTracer);
      }
    }
    animateTracer();
  }

  // 爆炸生成粒子
  function explode(x, y) {
    var count = 80 + Math.random() * 40;
    for (var i = 0; i < count; i++) {
      var angle = Math.random() * Math.PI * 2;
      var speed = 2 + Math.random() * 6;
      var size = 1.5 + Math.random() * 2.5;
      var life = 60 + Math.random() * 40;
      var color = COLORS[Math.floor(Math.random() * COLORS.length)];
      particles.push(new Particle(x, y, color, angle, speed, size, life));
    }
  }

  // 主循環
  function loop() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    for (var i = particles.length - 1; i >= 0; i--) {
      var p = particles[i];
      p.update();
      p.draw();
      if (p.life <= 0 || p.y > window.innerHeight + 50 || p.x < -50 || p.x > window.innerWidth + 50) {
        particles.splice(i, 1);
      }
    }
    requestAnimationFrame(loop);
  }
  loop();

  // 點擊觸發
  document.addEventListener('click', function (e) {
    launch(e.clientX, e.clientY);
  });

  // 觸控支援
  document.addEventListener('touchstart', function (e) {
    if (e.touches[0]) launch(e.touches[0].clientX, e.touches[0].clientY);
  }, {passive: true});
})();
</script>
</body>
</html>

關鍵優化點

  • requestAnimationFrame 替代 setInterval,與瀏覽器重繪同步,省電流暢
  • 高 DPI 適配:canvas.width = cssWidth * dpr,ctx.scale(dpr, dpr)
  • 對象池模式:大量粒子時預分配陣列複用,減少 GC(進階優化)
  • 離屏清理:超出視口範圍立即 splice 移除
  • globalAlpha 代替漸變填充,效能更優

進階擴展方向

方向實現思路
煙花形狀心形、笑臉、文字:粒子初始角度按數學函數分佈
聲音同步Web Audio API 合成爆炸音效,AudioContext 控制
轨迹尾跡粒子保存歷史位置陣列,繪製連線或漸變尾巴
風場影響引入 Perlin Noise 風場,粒子速度疊加風向向量
WebGL 版本百萬級粒子,GPU 並行計算,使用 Three.js / PixiJS / 原生 WebGL

結語

煙花特效是學習 Canvas 粒子系統、動畫循環、物理模擬的絕佳切入點。從本文的原生實現出發,你可以輕鬆擴展出粒子背景、魔法特效、數據可視化粒子流等豐富應用。記住核心三要素:**狀態更新 → 邊界檢查 → 重繪**,構建所有動畫系統的基石。

copyright © 萬盛學電腦網 all rights reserved