Particle Engine
Fast reusable effects (explosions, sparks, smoke, dust, confetti) with a fixed memory budget, so effects never slow the game by piling up.
Files: particle-engine.js (the component, no dependencies) and particle-engine.test.mjs (7 tests).
Copy particle-engine.js into your game, for example to src/components/, and import it as an ES module.
Usage
import { createParticles, PRESETS } from "./particle-engine.js";
const fx = createParticles({ max: 800 });
fx.emit(enemy.x, enemy.y, "explosion"); // a preset
fx.emit(x, y, { ...PRESETS.sparks, colors: ["#fff"] }, 12); // or your own settings
function frame(dt) { fx.update(dt); fx.draw(ctx); }
API
createParticles({ max, random }) → fxfx.emit(x, y, presetNameOrOptions, count) → number actually made (stops at max; oldest aren't replaced)options: count, speed [min,max], angle (radians, 0 = right), spread (radians, 2π = all round), life [min,max] seconds, size [start,end], colors […], gravity (px/s²), drag (0..1 per second lost), shape “circle” | “square”, additive (bool)fx.update(dt) / fx.draw(ctx) / fx.clear()fx.countlive particlesfx.forEach(fn)fn({ x, y, size, color, alpha, shape }) for drawing with another rendererfx.scalemultiply all counts (set to 0.3 on slow phones, 0 to turn effects off)
PRESETS: explosion, sparks, smoke, dust, confetti, trail
Engines
| Engine | Notes |
|---|---|
| Vanilla / Canvas 2D | draw(ctx) does everything. |
| Phaser | use Phaser’s particle emitters, or run this and draw with forEach into a Graphics object. |
| PixiJS | run update(), then forEach into a ParticleContainer of sprites (reuse sprites by index). |
| Three.js | run update(), then forEach into a Points geometry’s position and color buffers. |
Tests
Node tests: presets, the max budget, life and fading, gravity, scale, forEach output, draw calls, seeded randomness.
Run them with node --test toolkit/components/particle-engine/ (Node 20 or newer, nothing to install).