萬盛學電腦網

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

HTML5 Canvas 粒子系統:用初中物理公式實現極致動感的文字/圖片粒子化動畫

粒子動畫看似炫酷,核心邏輯卻只需初中物理:加速度、速度、位移、向量分解。本文拆解一個「文字粒子聚合」開場動畫的完整實現,展示「小公式、大樂趣」的編程美學。

粒子球體效果

核心物理模型:雙狀態運動

每個粒子擁有兩種狀態,由 globleDown 標記切換:

  1. 吸引態:受目標位置吸引,做變加速度運動;
  2. 自由落體態:脫離目標後,僅受重力與阻尼,做拋物線運動並最終落地彈跳。

粒子類定義


class Particle {
  constructor(x, y, vx, vy, targetX, targetY, color) {
    this.x = x; this.y = y;
    this.vx = vx; this.vy = vy;
    this.targetX = targetX; this.targetY = targetY;
    this.color = color;
    this.visible = true;
    this.attracted = true; // 是否處於吸引態
  }

  // 設置新目標位置
  setTarget(tx, ty) {
    this.targetX = tx; this.targetY = ty;
  }

  update(dt) {
    if (this.attracted && this.y <= this.targetY) {
      // === 吸引階段:向目標加速 ===
      const dx = this.targetX - this.x;
      const dy = this.targetY - this.y;
      const dist = Math.hypot(dx, dy);
      if (dist < 1) { this.attracted = false; return; } // 到達目標

      const ACCEL = 20; // 加速度大小
      const ax = ACCEL * dx / dist;
      const ay = ACCEL * dy / dist;
      const DAMP = 0.97; // 能量損耗係數

      this.vx = (this.vx + ax * dt) * DAMP;
      this.vy = (this.vy + ay * dt) * DAMP;
    } else {
      // === 自由落體階段 ===
      this.attracted = false;
      const GRAVITY = 9.8;
      this.vy += GRAVITY * dt;
      this.vx *= 0.99; // 水平阻力

      // 地面反彈
      if (this.y > canvas.height - 1) {
        this.y = canvas.height - 1;
        this.vy = -this.vy * 0.7; // 彈力係數
      }
    }

    // 位置積分
    this.x += this.vx * dt;
    this.y += this.vy * dt;
  }

  draw(ctx) {
    if (!this.visible) return;
    ctx.fillStyle = this.color;
    ctx.beginPath();
    ctx.arc(this.x, this.y, 2, 0, Math.PI * 2);
    ctx.fill();
  }
}

文字/圖片 → 粒子數據提取


function extractParticlesFromText(text, font, color) {
  // 1. 離屏 Canvas 繪製文字
  const offCanvas = document.createElement('canvas');
  offCanvas.width = 800; offCanvas.height = 200;
  const octx = offCanvas.getContext('2d');
  octx.font = font;
  octx.textAlign = 'center';
  octx.textBaseline = 'middle';
  octx.fillStyle = color;
  octx.fillText(text, offCanvas.width/2, offCanvas.height/2);

  // 2. 讀取像素數據
  const imgData = octx.getImageData(0, 0, offCanvas.width, offCanvas.height);
  const particles = [];
  const step = 3; // 採樣間距,控制粒子數量/性能

  for (let y = 0; y < offCanvas.height; y += step) {
    for (let x = 0; x < offCanvas.width; x += step) {
      const i = (y * offCanvas.width + x) * 4;
      const alpha = imgData.data[i + 3];
      if (alpha > 128) { // 有繪製內容
        const r = imgData.data[i], g = imgData.data[i+1], b = imgData.data[i+2];
        particles.push(new Particle(
          // 隨機初始位置(屏幕上方/兩側)
          Math.random() > 0.5 ? Math.random() * 100 : canvas.width - Math.random() * 100,
          -Math.random() * canvas.height * 2,
          0, 0, // 初始速度為 0
          // 目標位置:居中對齊
          x + (canvas.width - offCanvas.width) / 2,
          y + (canvas.height - offCanvas.height) / 2,
          `rgba(${r},${g},${b},1)`
        ));
      }
    }
  }
  return particles;
}

動畫主循環


const particles = extractParticlesFromText('Welcome', '70px Microsoft YaHei', '#1D181F');
let last = performance.now();

function animate(now) {
  const dt = (now - last) / 1000;
  last = now;

  ctx.fillStyle = 'rgba(255,255,255,0.1)'; // 拖尾效果
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  particles.forEach(p => {
    p.update(dt);
    p.draw(ctx);
  });

  requestAnimationFrame(animate);
}

animate(performance.now());

擴展玩法

  • 3D 粒子球:初始化時將粒子均勻分布在球面(費波那螺旋算法),z 軸決定大小/透明度,旋轉矩陣更新位置;
  • 流場:Perlin Noise 生成向量場,粒子跟隨場線運動,產生「風/水」流動感;
  • GPU 加速:將位置/速度存入 Texture,Vertex Shader 計算物理,Fragment Shader 渲染點精靈,支撐 100 萬+ 粒子;
  • 互動:滑鼠位置作為動態目標點,粒子跟隨/逃離/環繞。

從「文字圖片像素採樣」到「牛頓運動定律迭代」,幾十行代碼構建出極具觀賞性的生成式藝術。這正是創意編程的魅力:**用最樸素的數學語言,寫出最動人的視覺詩篇。**

copyright © 萬盛學電腦網 all rights reserved