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

每個粒子擁有兩種狀態,由 globleDown 標記切換:
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());
z 軸決定大小/透明度,旋轉矩陣更新位置;從「文字圖片像素採樣」到「牛頓運動定律迭代」,幾十行代碼構建出極具觀賞性的生成式藝術。這正是創意編程的魅力:**用最樸素的數學語言,寫出最動人的視覺詩篇。**