Particles - BaryoDev/dopaminejs GitHub Wiki

Particles

ParticleSystem draws on a 2D canvas that it creates and owns.

import { ParticleSystem } from 'dopaminejs';

const particles = new ParticleSystem();
particles.confetti(window.innerWidth / 2, 200);

The constructor takes a config object, not a canvas.

Config

Option Default Meaning
container document.body An element or a selector
canvasId 'dopamine-particle-canvas' Id of the canvas
zIndex '9999' Stacking order
maxParticles 5000 Live particle cap
respectReducedMotion true Drop effects when the user asks for reduced motion

On body the canvas is fixed and covers the viewport. Inside another container it is absolutely positioned, and a container with static positioning is switched to position: relative.

The canvas ignores pointer events. Coordinates are CSS pixels relative to the canvas.

Built-in effects

Method Default count
confetti(x, y, count) 50
coinShower(x, y, count) 10
sparkle(x, y, count, color) 20
fire(x, y, count) 15
starBurst(x, y, count) 8

emit

particles.emit({
    x: 300,
    y: 200,
    count: 40,
    speed: 6,
    gravity: 0.15,
    decay: 0.02,
    life: 1.0,
    color: ['#ff4d6d', '#ffd166', '#06d6a0'],
    spread: Math.PI / 2,
    angle: -Math.PI / 2,
    size: 5
});
Option Default Meaning
x, y required Origin
count 10 Particles to add
speed 5 Pixels per frame at 60 Hz
gravity 0.1 Added to vertical speed each frame
decay 0.02 Life lost each frame
life 1.0 Starting life. The particle is removed at 0.
color '#ffd700' A string, or an array to pick from at random
spread 2 * Math.PI Arc width in radians
angle 0 Centre of the arc in radians
size 5 Pixels
sprite none Key of a registered sprite to draw instead of a circle

Speeds are written per 60 Hz frame and scaled by the real frame time, so effects run at the same speed on a 120 Hz screen.

Custom effects

particles.registerEffect('heart', (x, y, count = 12) => {
    particles.emit({ x, y, count, color: '#ff4d6d', speed: 3, gravity: -0.05 });
});

particles.play('heart', 300, 200);
particles.play('heart', 300, 200, 30);   // extra arguments are passed through

play with an unknown name logs a warning and does nothing.

Sprites

particles.registerSprite('coin', '/img/coin.png');
particles.emit({ x: 300, y: 200, sprite: 'coin', size: 24 });

Limits

  • Past maxParticles, new particles are dropped.
  • Under prefers-reduced-motion, emit does nothing unless respectReducedMotion is false.
  • The animation loop stops when no particles are alive.

Cleanup

particles.clear();     // drop live particles
particles.destroy();   // stop the loop, remove the canvas and the resize listener

More particles

For tens of thousands of particles use Plugin: WebGL Particles. It has a different emit shape and cannot be passed to GameUI.