FUN INTERACTIVE
PARTICLE SYSTEM
By Shane Brumback · · Updated · Free Three.js tutorial · Level 1
To make an interactive particle system in Three.js, give every particle a home position and a velocity, then each frame pull it toward home with a spring and push it away from the mouse. Here 160 glowing smiley sprites scatter from your cursor or finger, wiggle when they get scared, and drift back into a cloud.
A beginner walkthrough of Sprite particles, a smiley face drawn on a CanvasTexture, pointer raycasting and simple spring physics in Three.js. Move your mouse over this page: the smileys behind it are the live demo.
LIVE DEMO
The smiley cloud behind this page is a live Three.js scene. Launch the full-screen demo to chase the smileys with your mouse or finger and click or tap to blast them apart. Launch asks for a free Google sign-in first. Press Esc or Exit to return.
Free Google sign-in · Move to scatter · Click to blast · Esc to exit
What Is a Particle System?
A particle system is a crowd of small, simple things that move together to make one effect: sparks, snow, smoke, stars, or in this case a cloud of happy faces. Each particle is cheap on its own. The magic comes from giving every one of them the same few rules and letting them run.
Three.js is a JavaScript library that draws 3D graphics in the browser with WebGL. It gives you several ways to draw particles. This tutorial uses THREE.Sprite, a flat picture that always turns to face the camera, so a smiley never looks edge-on. For tens of thousands of dots you would switch to THREE.Points, which the simple particle system tutorial covers.
The Three Rules That Make It Feel Alive
1. Go home. Every smiley remembers where it was born. A spring pulls it back there, harder the farther away it is.
2. Run from the hand. We turn your mouse or finger into a point in the 3D world. Any smiley closer than 2.6 units gets pushed straight away from it, and the push gets stronger the closer you are.
3. Calm down. Damping slowly drains speed every frame, so smileys glide to a stop instead of bouncing forever. Add a little wobble and a scared wiggle, and a few lines of math feel like a living swarm. Want them to pop and score points instead? That is the interactive smiley particle game.
Step-by-Step Code Breakdown
Every excerpt below is copied exactly from the full code further down.
1. Set up the scene, camera and renderer
In plain words: we make an empty dark 3D world, a camera looking at it and a renderer that draws it onto the page. Create a Scene with a near-black background, a PerspectiveCamera 14 units back, and a WebGLRenderer sized to the window with the pixel ratio capped at 2.
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x05060c);
const camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 0.1, 200);
camera.position.set(0, 0, 14);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
document.body.style.margin = '0';
document.body.appendChild(renderer.domElement);
2. Draw a smiley face texture on a canvas
In plain words: instead of loading an image file, we paint a white smiley with a soft glow on a tiny hidden canvas and use it as a picture. Use the 2D canvas API to draw a radial glow, a white circle, two eyes and a smile, then wrap the canvas in a CanvasTexture with sRGB color space.
function makeSmileyTexture() {
const c = document.createElement('canvas');
c.width = c.height = 128;
const g = c.getContext('2d');
const glow = g.createRadialGradient(64, 64, 34, 64, 64, 64);
glow.addColorStop(0, 'rgba(255,255,255,0.6)');
glow.addColorStop(1, 'rgba(255,255,255,0)');
g.fillStyle = glow;
g.fillRect(0, 0, 128, 128);
g.fillStyle = '#ffffff';
g.beginPath(); g.arc(64, 64, 40, 0, Math.PI * 2); g.fill();
g.fillStyle = '#111111';
g.beginPath(); g.ellipse(50, 53, 5, 8, 0, 0, Math.PI * 2); g.fill();
g.beginPath(); g.ellipse(78, 53, 5, 8, 0, 0, Math.PI * 2); g.fill();
g.strokeStyle = '#111111';
g.lineWidth = 6;
g.lineCap = 'round';
g.beginPath(); g.arc(64, 64, 23, 0.18 * Math.PI, 0.82 * Math.PI); g.stroke();
const texture = new THREE.CanvasTexture(c);
texture.colorSpace = THREE.SRGBColorSpace;
return texture;
}
3. Create the smiley sprites with a home position
In plain words: we make 160 smileys in seven bright colors, scatter them in a ball shape, and let each one remember its home spot. Give each Sprite its own SpriteMaterial tinted with a color, place it at a random point inside a sphere, and store its home, velocity, size and wobble phase.
const COLORS = [0xffd400, 0x39ff14, 0xff3df0, 0x2a8cff, 0xff7a00, 0x00e5ff, 0xff2d55];
const COUNT = isMobile ? 90 : 160;
const smileyTexture = makeSmileyTexture();
const cluster = new THREE.Group();
scene.add(cluster);
const particles = [];
for (let i = 0; i < COUNT; i++) {
const material = new THREE.SpriteMaterial({
map: smileyTexture,
color: COLORS[i % COLORS.length],
transparent: true,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
const home = new THREE.Vector3().randomDirection().multiplyScalar(1 + Math.cbrt(Math.random()) * 4.2);
home.y *= 0.85;
sprite.position.copy(home);
const size = 0.55 + Math.random() * 0.55;
sprite.scale.setScalar(size);
cluster.add(sprite);
particles.push({ sprite, home, velocity: new THREE.Vector3(), size, phase: Math.random() * Math.PI * 2 });
}
4. Turn the mouse or finger into a 3D point
In plain words: we listen for the pointer and remember where it is on screen, so later we can shoot a ray from the camera through it. Store pointer coordinates as normalized device coordinates from -1 to 1, and keep a Raycaster and a Plane at z = 0 to find where the pointer meets the cloud.
const pointer = new THREE.Vector2();
const raycaster = new THREE.Raycaster();
const pointerPlane = new THREE.Plane(new THREE.Vector3(0, 0, 1), 0);
const hand = new THREE.Vector3();
const handLocal = new THREE.Vector3();
let pointerActive = false;
addEventListener('pointermove', (e) => {
pointer.set((e.clientX / innerWidth) * 2 - 1, -(e.clientY / innerHeight) * 2 + 1);
pointerActive = true;
});
document.addEventListener('pointerleave', () => { pointerActive = false; });
5. Click or tap to blast the cloud apart
In plain words: a click finds the 3D spot under your finger and kicks every nearby smiley away from it. On pointerdown, intersect the ray with the plane, convert the hit into the cluster local space with worldToLocal, and add an outward velocity to particles within 5 units.
addEventListener('pointerdown', (e) => {
pointer.set((e.clientX / innerWidth) * 2 - 1, -(e.clientY / innerHeight) * 2 + 1);
raycaster.setFromCamera(pointer, camera);
if (!raycaster.ray.intersectPlane(pointerPlane, hand)) return;
cluster.worldToLocal(handLocal.copy(hand));
for (const p of particles) {
const away = p.sprite.position.clone().sub(handLocal);
const d = away.length();
if (d < 5) p.velocity.add(away.normalize().multiplyScalar((5 - d) * 6));
}
});
6. Spring home, flee the hand and wiggle
In plain words: each frame every smiley is pulled home, pushed away from your hand if it is close, slowed down a little, and wiggles more when it is scared. Add a spring force toward home, a repel force that grows as distance shrinks, exponential damping, then scale and rotate each sprite from its fear value.
const REPEL_RADIUS = 2.6, REPEL_FORCE = 60, SPRING = 4, DAMPING = 3.2;
function updateParticles(dt, t) {
if (pointerActive) {
raycaster.setFromCamera(pointer, camera);
if (raycaster.ray.intersectPlane(pointerPlane, hand)) cluster.worldToLocal(handLocal.copy(hand));
} else {
handLocal.set(Math.cos(t * 0.7) * 3.5, Math.sin(t * 1.1) * 2.5, 2);
}
const push = new THREE.Vector3();
for (const p of particles) {
const pos = p.sprite.position;
push.copy(p.home).sub(pos).multiplyScalar(SPRING);
const away = pos.clone().sub(handLocal);
const d = away.length();
let fear = 0;
if (d < REPEL_RADIUS) {
fear = 1 - d / REPEL_RADIUS;
push.add(away.normalize().multiplyScalar(fear * REPEL_FORCE));
}
p.velocity.addScaledVector(push, dt);
p.velocity.multiplyScalar(Math.exp(-DAMPING * dt));
pos.addScaledVector(p.velocity, dt);
const wobble = 1 + Math.sin(t * 3 + p.phase) * 0.06 + fear * 0.45;
p.sprite.scale.setScalar(p.size * wobble);
p.sprite.material.rotation = Math.sin(t * 2 + p.phase) * 0.25 + fear * Math.sin(t * 30) * 0.4;
}
}
7. Run the render loop
In plain words: every frame we move time forward, sway the whole cloud, update the smileys and draw the picture. Use a Clock with a capped delta, gently rotate the cluster, call updateParticles, render, and resize the camera and renderer with the window.
const clock = new THREE.Clock();
function render() {
requestAnimationFrame(render);
const dt = Math.min(clock.getDelta(), 0.05);
const t = clock.elapsedTime;
cluster.rotation.y = Math.sin(t * 0.15) * 0.5;
updateParticles(dt, t);
renderer.render(scene, camera);
}
render();
addEventListener('resize', () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
});
When no pointer is over the page, the hand point takes a slow figure-eight path so the cloud keeps moving on its own. Next, try thousands of dots with a simple particle system, or bounce particles off a moving collider in exploring interactive visual particle systems.
The Full Code
Paste this module into a page with the same import map as this one (Three.js 0.160 from unpkg). The smiley texture is drawn in code, so there are no image files to download.
import * as THREE from 'three';
const isMobile = matchMedia('(max-width: 768px)').matches;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x05060c);
const camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 0.1, 200);
camera.position.set(0, 0, 14);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
document.body.style.margin = '0';
document.body.appendChild(renderer.domElement);
function makeSmileyTexture() {
const c = document.createElement('canvas');
c.width = c.height = 128;
const g = c.getContext('2d');
const glow = g.createRadialGradient(64, 64, 34, 64, 64, 64);
glow.addColorStop(0, 'rgba(255,255,255,0.6)');
glow.addColorStop(1, 'rgba(255,255,255,0)');
g.fillStyle = glow;
g.fillRect(0, 0, 128, 128);
g.fillStyle = '#ffffff';
g.beginPath(); g.arc(64, 64, 40, 0, Math.PI * 2); g.fill();
g.fillStyle = '#111111';
g.beginPath(); g.ellipse(50, 53, 5, 8, 0, 0, Math.PI * 2); g.fill();
g.beginPath(); g.ellipse(78, 53, 5, 8, 0, 0, Math.PI * 2); g.fill();
g.strokeStyle = '#111111';
g.lineWidth = 6;
g.lineCap = 'round';
g.beginPath(); g.arc(64, 64, 23, 0.18 * Math.PI, 0.82 * Math.PI); g.stroke();
const texture = new THREE.CanvasTexture(c);
texture.colorSpace = THREE.SRGBColorSpace;
return texture;
}
const COLORS = [0xffd400, 0x39ff14, 0xff3df0, 0x2a8cff, 0xff7a00, 0x00e5ff, 0xff2d55];
const COUNT = isMobile ? 90 : 160;
const smileyTexture = makeSmileyTexture();
const cluster = new THREE.Group();
scene.add(cluster);
const particles = [];
for (let i = 0; i < COUNT; i++) {
const material = new THREE.SpriteMaterial({
map: smileyTexture,
color: COLORS[i % COLORS.length],
transparent: true,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
const home = new THREE.Vector3().randomDirection().multiplyScalar(1 + Math.cbrt(Math.random()) * 4.2);
home.y *= 0.85;
sprite.position.copy(home);
const size = 0.55 + Math.random() * 0.55;
sprite.scale.setScalar(size);
cluster.add(sprite);
particles.push({ sprite, home, velocity: new THREE.Vector3(), size, phase: Math.random() * Math.PI * 2 });
}
const stars = new THREE.BufferGeometry();
const starPositions = [];
for (let i = 0; i < 1500; i++) {
starPositions.push((Math.random() - 0.5) * 160, (Math.random() - 0.5) * 100, -20 - Math.random() * 60);
}
stars.setAttribute('position', new THREE.Float32BufferAttribute(starPositions, 3));
scene.add(new THREE.Points(stars, new THREE.PointsMaterial({ color: 0x8899ff, size: 0.15 })));
const pointer = new THREE.Vector2();
const raycaster = new THREE.Raycaster();
const pointerPlane = new THREE.Plane(new THREE.Vector3(0, 0, 1), 0);
const hand = new THREE.Vector3();
const handLocal = new THREE.Vector3();
let pointerActive = false;
addEventListener('pointermove', (e) => {
pointer.set((e.clientX / innerWidth) * 2 - 1, -(e.clientY / innerHeight) * 2 + 1);
pointerActive = true;
});
document.addEventListener('pointerleave', () => { pointerActive = false; });
addEventListener('pointerdown', (e) => {
pointer.set((e.clientX / innerWidth) * 2 - 1, -(e.clientY / innerHeight) * 2 + 1);
raycaster.setFromCamera(pointer, camera);
if (!raycaster.ray.intersectPlane(pointerPlane, hand)) return;
cluster.worldToLocal(handLocal.copy(hand));
for (const p of particles) {
const away = p.sprite.position.clone().sub(handLocal);
const d = away.length();
if (d < 5) p.velocity.add(away.normalize().multiplyScalar((5 - d) * 6));
}
});
const REPEL_RADIUS = 2.6, REPEL_FORCE = 60, SPRING = 4, DAMPING = 3.2;
function updateParticles(dt, t) {
if (pointerActive) {
raycaster.setFromCamera(pointer, camera);
if (raycaster.ray.intersectPlane(pointerPlane, hand)) cluster.worldToLocal(handLocal.copy(hand));
} else {
handLocal.set(Math.cos(t * 0.7) * 3.5, Math.sin(t * 1.1) * 2.5, 2);
}
const push = new THREE.Vector3();
for (const p of particles) {
const pos = p.sprite.position;
push.copy(p.home).sub(pos).multiplyScalar(SPRING);
const away = pos.clone().sub(handLocal);
const d = away.length();
let fear = 0;
if (d < REPEL_RADIUS) {
fear = 1 - d / REPEL_RADIUS;
push.add(away.normalize().multiplyScalar(fear * REPEL_FORCE));
}
p.velocity.addScaledVector(push, dt);
p.velocity.multiplyScalar(Math.exp(-DAMPING * dt));
pos.addScaledVector(p.velocity, dt);
const wobble = 1 + Math.sin(t * 3 + p.phase) * 0.06 + fear * 0.45;
p.sprite.scale.setScalar(p.size * wobble);
p.sprite.material.rotation = Math.sin(t * 2 + p.phase) * 0.25 + fear * Math.sin(t * 30) * 0.4;
}
}
const clock = new THREE.Clock();
function render() {
requestAnimationFrame(render);
const dt = Math.min(clock.getDelta(), 0.05);
const t = clock.elapsedTime;
cluster.rotation.y = Math.sin(t * 0.15) * 0.5;
updateParticles(dt, t);
renderer.render(scene, camera);
}
render();
addEventListener('resize', () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
});
Frequently Asked Questions
What is a particle system in Three.js?
A particle system is many small objects, such as sprites or points, that follow the same simple rules to create one effect like sparks, snow, stars or a swarm. In Three.js you can build one with Sprite objects, a Points cloud or an InstancedMesh, and update their positions every frame.
How do you make particles react to the mouse in Three.js?
Convert the pointer to normalized device coordinates, use Raycaster.setFromCamera to shoot a ray through it, and intersect that ray with a plane to get a 3D point. Each frame, push any particle closer than a set radius away from that point.
Why do the smileys spring back to their place?
Each particle stores a home position. Every frame a spring force proportional to the distance from home is added to its velocity, and damping removes a little speed, so it glides back and settles instead of flying away.
Should I use Sprite or Points for particles?
Sprites are easy and let every particle have its own color, size and rotation, which is great for a few hundred. Points draws thousands or millions in one draw call but shares one material, so use it for big clouds of dots.
Does the demo work on phones?
Yes. Pointer events cover mouse, pen and touch, so dragging a finger scatters the smileys and a tap blasts them. The demo also uses fewer particles on small screens to stay smooth.
Why do I need to sign in to launch the live demo?
The tutorial and its full code are free to read. The full-screen Live Demo asks for a free Google sign-in first, the same gate used across the site.
Play It and Keep Learning
Particles, sprites and pointer input like this power the effects in Super Soldier Battle, a free Three.js browser game. Browse every Three.js tutorial, read the articles, or search the site.
Need Three.js or WebGL work for your site or game? I take freelance and contract work: contact me.
Play Game