Skip to content

Particle Explosion

Click the canvas to spawn a burst of short-lived particles with gravity.

Paste into main.js in the editor, then click Restart. Click the canvas to explode.

Complete example

javascript
if (!state.init) {
  state.init = true;
  state.particles = [];
}

if (state.clickX !== undefined) {
  for (let i = 0; i < 30; i++) {
    const angle = Math.random() * Math.PI * 2;
    const speed = 50 + Math.random() * 200;
    state.particles.push({
      x: state.clickX,
      y: state.clickY,
      vx: Math.cos(angle) * speed,
      vy: Math.sin(angle) * speed,
      life: 1,
      decay: 0.3 + Math.random() * 0.7,
      r: 2 + Math.random() * 4,
      color: ['#8B5CF6', '#F59E0B', '#EF4444', '#22C55E', '#3B82F6'][
        Math.floor(Math.random() * 5)
      ],
    });
  }
  state.clickX = undefined;
  state.clickY = undefined;
}

state.particles = state.particles.filter((p) => {
  p.vy += 100 * dt;
  p.x += p.vx * dt;
  p.y += p.vy * dt;
  p.life -= p.decay * dt;
  return p.life > 0;
});

return {
  particles: state.particles.map((p) => ({
    x: p.x, y: p.y, r: p.r * p.life, color: p.color,
  })),
  lines: [
    { x1: 0, y1: h - 20, x2: w, y2: h - 20, color: 'rgba(255,255,255,0.1)', width: 1 },
  ],
  text: {
    particles: state.particles.length,
    hint: 'Click to explode!',
  },
};

Patterns used

  1. Consume click — clear clickX/clickY or the burst repeats every frame
  2. Lifetimelife from 1 → 0; remove when ≤ 0
  3. Visual fade — radius scales with life
  4. Filterfilter both updates and removes dead particles

WARNING

Rapid clicking can spawn thousands of particles. Cap with if (state.particles.length > 800) return before pushing, or recycle from a pool (see Performance).

Try next

  • Bounce on the floor line
  • Emit continuously while holding a “rate” timer (state.emitTimer)
  • Map life into alpha: color: `rgba(139,92,246,${p.life})`