The first version of my portfolio had a giant "4" built out of 15,000 floating particles that moved around, responded to the mouse and changed their shape. I have since rebuilt this site (read why). However, the technique is still sound. Let me explain how I made it.
The Problem
The first thing you have to do is sample points from a font glyph. You can't just take the glyph and have particles at every pixel. The glyph is a vector path, so you need to take that and turn it into thousands of 3D positions. I did this by taking the glyph and rendering it to a canvas. Then reading the pixel data from the canvas to get points where the pixel isn't transparent.
// In a web worker
const canvas = new OffscreenCanvas(width, height);
const ctx = canvas.getContext("2d");
ctx.font = `${fontSize}px Outfit`;
ctx.fillText("4", 0, fontSize);
const imageData = ctx.getImageData(0, 0, width, height);
const points: [number, number, number][] = [];
for (let y = 0; y < height; y += step) {
for (let x = 0; x < width; x += step) {
const alpha = imageData.data[(y * width + x) * 4 + 3];
if (alpha > 128) {
points.push([x - width/2, -(y - height/2), 0]);
}
}
}
That gives you a dense grid of points, except there's a problem.
The Clipping Bug
The first version of this site sampled points sequentially. "Just take the first 15,000 points from the grid." That works if you have more points than particles, but since I had to downsample to 8,000 particles on mobile because the mobile browser was too slow, sampling points sequentially from an ordered grid meant that when I sampled 8,000 particles, I only got the top parts of the glyph. All the points at the bottom of the glyph were lost. It was like my "4" only had a head and an upper body. My "4" had lost its foot.
The Solution
The solution is simple: random sampling.
// Shuffle the points array, then take the first N
function seededShuffle(arr: any[], seed: number) {
let m = arr.length;
while (m) {
const i = Math.floor(seededRandom(seed++) * m--);
[arr[m], arr[i]] = [arr[i], arr[m]];
}
return arr;
}
const sampled = seededShuffle([...points], 42).slice(0, particleCount);
Seeded random sampling, to be precise, so your results are deterministic, repeatable each time you run the code so that the shape of the particles doesn't change between renders, but also so that you have a uniform distribution of points across the entire glyph, no matter how many particles you have.
Web Worker for Performance
Sampling the points takes ~50 milliseconds on the desktop, ~200 milliseconds on the mobile browser. That's too long for the main thread to block while the site loads. So I moved this into a web worker. The computation of the position of each particle happens in the background while your site is rendering. Once the worker is complete, the particles are rendered smoothly.
// Main thread
const worker = new Worker(new URL("./particle-worker.ts", import.meta.url));
worker.postMessage({ glyph: "4", count: 15000, width: 800 });
worker.onmessage = (e) => setPositions(e.data.positions);
Mouse Interaction
Particles should move away from the cursor when the cursor is near them. The physics is just simple: get the distance between cursor and particle, calculate a repulsion force that falls off with the distance.
// In the animation loop
const dx = mouseX - particle.x;
const dy = mouseY - particle.y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < repulsionRadius) {
const force = (1 - dist / repulsionRadius) * strength;
particle.vx -= (dx / dist) * force;
particle.vy -= (dy / dist) * force;
}
// Spring back to original position
particle.vx += (particle.originX - particle.x) * springStrength;
particle.vy += (particle.originY - particle.y) * springStrength;
// Damping
particle.vx *= 0.95;
particle.vy *= 0.95;
A spring force to draw the particles back to where they were. A damping force to prevent particles from vibrating back and forth forever. It makes sense in real life, when you push particles away, they should flow back to where they were.
Mobile: Touch Instead of Mouse
Also, I implemented double tap to activate morph effect and touchmove to interact. I have made the physics constants depend on the size of the viewport so that the effect is neither too weak or too strong on different devices.
Performance
- Desktop (1920px): 15,000 particles at 60fps
- Laptop (1440px): 12,000 particles at 60fps
- Tablet: 10,000 particles at 55-60fps
- Mobile: 8,000 particles at 50-60fps
Also, I scaled the particles' size as well. Particles < 1px will not be drawn at the screen edges on some devices depending on the GPU. I also set the min size of particles to be dependent on devicePixelRatio.