本文详解如何基于 canvas api,利用对象数组高效创建、更新和渲染多个粒子(圆形形状),并内置物理属性(速度、加速度、摩擦力、生命周期)以支持真实碰撞模拟,彻底告别重复手写绘图代码。
本文详解如何基于 canvas api,利用对象数组高效创建、更新和渲染多个粒子(圆形形状),并内置物理属性(速度、加速度、摩擦力、生命周期)以支持真实碰撞模拟,彻底告别重复手写绘图代码。
在 Canvas 中批量绘制形状(尤其是用于粒子模拟的动态对象),核心在于将状态与行为封装为可复用的对象,并统一由数组管理其生命周期。你原代码中尝试用 objects[i] = new component(...) 创建实例的方向完全正确,但存在几个关键问题:updateGameArea 中未遍历数组、component 缺少物理逻辑、且未实现碰撞检测机制。下面我们将构建一个轻量但完整的粒子系统教程。
✅ 正确结构:类封装 + 数组驱动 + 游戏循环
首先,定义 Particle 类,它不仅存储位置/颜色等视觉属性,还包含运动学逻辑:
class Particle {
constructor(x, y, radius, color) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
// 物理属性(可后续扩展碰撞)
this.vx = (Math.random() - 0.5) * 4; // 水平初速度
this.vy = (Math.random() - 0.5) * 4; // 垂直初速度
this.ax = 0;
this.ay = 0.05; // 向下重力
this.friction = 0.98;
}
update() {
this.vx += this.ax;
this.vy += this.ay;
this.vx *= this.friction;
this.vy *= this.friction;
this.x += this.vx;
this.y += this.vy;
// 边界反弹(简易碰撞)
const canvas = document.getElementById('c');
if (this.x - this.radius < 0 || this.x + this.radius > canvas.width) {
this.vx *= -0.8;
this.x = this.x < this.radius ? this.radius : canvas.width - this.radius;
}
if (this.y - this.radius < 0 || this.y + this.radius > canvas.height) {
this.vy *= -0.8;
this.y = this.y < this.radius ? this.radius : canvas.height - this.radius;
}
}
draw(ctx) {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
ctx.closePath();
}
}✅ 批量创建:用数组统一初始化与管理
不再手动写 40 行 new Particle(...),而是通过循环+配置数组生成:
const canvas = document.getElementById('c');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 配置粒子池:每个对象定义初始参数
const particleConfigs = [
{ x: 100, y: 100, r: 8, c: '#ff6b6b' },
{ x: 200, y: 150, r: 6, c: '#4ecdc4' },
{ x: 300, y: 80, r: 10, c: '#ffe66d' },
// 可无限追加,甚至用循环自动生成
];
// 批量创建粒子实例
const particles = particleConfigs.map(cfg =>
new Particle(cfg.x, cfg.y, cfg.r, cfg.c)
);
// 或更灵活地生成 50 个随机粒子:
for (let i = 0; i < 50; i++) {
particles.push(new Particle(
Math.random() * canvas.width,
Math.random() * canvas.height,
Math.random() * 4 + 2,
`hsl(${Math.random() * 360}, 70%, 60%)`
));
}✅ 渲染与更新:游戏循环中遍历数组
使用 requestAnimationFrame 替代 setInterval,确保流畅性与性能:
function clearCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
function updateAll() {
particles.forEach(p => p.update());
}
function renderAll() {
particles.forEach(p => p.draw(ctx));
}
function gameLoop() {
clearCanvas();
updateAll();
renderAll();
requestAnimationFrame(gameLoop);
}
// 启动
gameLoop();⚠️ 关键注意事项
- 不要在 updateGameArea 中使用未声明的 i:你原代码 objects[i].update() 中 i 未定义,应改为 objects.forEach(obj => obj.update())。
- Canvas 清屏必须在每一帧开头调用:否则会残留轨迹(ctx.clearRect() 或 fillRect() 背景色)。
- 碰撞逻辑需在 update() 内完成:如上例中的边界反弹,真实粒子碰撞需额外实现距离检测与动量守恒(可基于 Math.hypot(dx, dy) < p1.radius + p2.radius 判断)。
- 内存管理:长期运行时建议定期清理已出界或死亡的粒子(例如添加 isDead() 方法并在 updateAll() 中 filter())。
✅ 总结:为什么这比“复制粘贴 40 行”更优?
| 维度 | 传统方式 | 数组+类驱动方式 |
|---|---|---|
| 可维护性 | 修改颜色/大小需改多处 | 改 Particle 类或配置数组即可全局生效 |
| 可扩展性 | 新增粒子=新增 5 行代码 | particles.push(new Particle(...)) |
| 性能 | 无统一管理,易产生冗余操作 | 单次遍历完成全部更新与渲染 |
| 物理一致性 | 每个粒子逻辑独立,难以同步 | 共享同一套物理规则,行为可预测 |
至此,你已掌握 Canvas 粒子系统的核心范式:数据驱动(数组)、面向对象(类)、时间驱动(游戏循环)。下一步可引入向量运算库、分离碰撞检测模块,或接入 Matter.js 等成熟物理引擎——但万变不离其宗:让数组成为你的粒子指挥中心。
















