The hero on anjay.dev starts as a drifting field of dots, glyphs and nodes, and as you scroll they assemble into text. It runs on phones, keeps scrolling smooth and never touches WebGL. This is the full technique for a canvas particle text animation, with the real code and the performance rules that keep it fast. Play with it first:
Interactive · type a word, watch it assemble
— fps1600 particles0 targets0 colour switches / frame
Try typing your own word, then push the particle count up and turn Batch by colour off. Watch the colour switches per frame jump from a handful to hundreds: that number is the most important idea in this article.
Step 1: draw the word once, offscreen
Particles need to know where the letters are. The simplest reliable way is to let the browser draw the text for you on a hidden canvas, in the same font as the page, and then read its pixels with getImageData:
const off = document.createElement('canvas')
off.width = W
off.height = H
const octx = off.getContext('2d', { willReadFrequently: true })!
octx.font = `600 ${fontSize}px ${displayFont}`
octx.textAlign = 'center'
octx.textBaseline = 'middle'
octx.fillStyle = '#fff'
octx.fillText(word, W / 2, H / 2)
const img = octx.getImageData(0, 0, W, H).data // RGBA bytesStep 2: sample the ink into targets
Every pixel would be far too many targets. Instead, walk a grid over the image and keep the points that land on ink. The grid step is not a magic number: it is derived from how much ink there is and how many particles you have, so a short word and a long word both end up well covered.
// Ink area → grid step that yields ≈ 82% of the particle count as targets
let ink = 0
for (let i = 3; i < img.length; i += 16) if (img[i] > 128) ink++
ink *= 4
const step = Math.max(2, Math.sqrt(ink / (n * 0.82)))
for (let y = step / 2; y < H; y += step) {
// Offset alternate rows → a finer, less mechanical dot-matrix
const rowShift = (Math.round(y / step) % 2) * step * 0.5
for (let x = step / 2 + rowShift; x < W; x += step) {
if (img[((y | 0) * W + (x | 0)) * 4 + 3] > 140) targets.push({ x, y })
}
}Two details matter. Reading every 4th pixel (i += 16) is enough to estimate ink area cheaply. And the staggered rows: switch on Sampling grid in the demo and you will see the targets form a honeycomb, which reads as a smoother letter than a square grid at the same density.
Roughly 18% of particles are left without a target on purpose. They drift outward as the word forms, so the letters sit in a quiet halo instead of a busy field.
Step 3: pair particles to targets
If particles pick random targets, their paths cross everywhere and the motion looks like static. Sort both lists left-to-right and pair them by rank: neighbours travel together, and the flow stays laminarSmooth, parallel motion without paths crossing, like layers of fluid sliding past each other..
// Targets left→right with a little noise; particles by their home x
const tKeys = targets.map((p, i) => ({ i, k: p.x + (rnd() - 0.5) * markWidth * 0.12 }))
tKeys.sort((a, b) => a.k - b.k)
particles.sort((a, b) => homeX[a] - homeX[b])
for (let j = 0; j < count; j++) {
const p = targets[tKeys[Math.floor((j * tKeys.length) / count)].i]
const i = particles[j]
tx[i] = p.x
ty[i] = p.y
}The small noise on the sort key is deliberate: a perfectly sorted mapping looks mechanical, like a printer. A little disorder makes it look hand-written.
Step 4: the writing wave
If every particle starts at once, the word just fades in. Giving each one a delay based on its target’s x position makes the left side depart first, so the word writes itself:
// Writing wave: left side departs first, with organic jitter
delay[i] = clamp01(nx * 0.62 + rnd() * 0.38) // nx = target x across the word, 0..1
// Per frame, each particle runs its own eased flight
const lp = clamp01((progress - convergeStart - delay[i] * spread) / flightTime)
const e = easeInOutCubic(lp)
x = lerp(homeX, targetX, e)
y = lerp(homeY, targetY, e)The 62/38 split is the whole personality of the effect: mostly ordered, a little alive. Push the jitter to 100% and it becomes a swarm; drop it to 0% and it becomes a wipe.
Step 5: one loop, frame-rate independent
On anjay.dev the animation is driven by scroll, but the scroll handler never draws. It only sets a target. One requestAnimationFrame loop eases the real progress towards it:
private frame = (now: number) => {
const dt = Math.min((now - this.last) / 1000, 0.1) // cap: a background tab never "jumps"
this.last = now
// Exponential smoothing that behaves the same at 60 Hz and 120 Hz
this.progress += (this.target - this.progress) * (1 - Math.exp(-dt * 6.5))
this.draw(this.progress, this.time, dt)
this.raf = requestAnimationFrame(this.frame)
}Staying fast: the performance budget
Everything above runs once per word. The frame loop is where performance is won or lost, and it follows a strict budget:
- Squares, not circles. At 2–3 px nobody can tell a square from a circle, and
fillRectskips path building entirely. Noarc()per particle. - Batch by colour. Changing
fillStyleis surprisingly costly. Sorting the draw order by colour once means a frame switches colour only a few times instead of thousands. The demo above counts it live. - Typed arrays. Positions, targets and delays live in
Float32Arrays, not arrays of objects: compact, cache-friendly, no garbage collection pauses mid-animation. - Sprites for anything complex. Code glyphs and glows are pre-drawn once into an atlas canvas and stamped with
drawImage, never re-rendered withfillTexteach frame. - A capped pixel ratio. The backing buffer is sized by
devicePixelRatio, but capped, because a 3× phone screen would otherwise mean 9× the pixels to clear every frame.
The particle count itself scales with the device. These are the real tiers from the hero:
| Screen | Dots | Pixel-ratio cap | Pointer effects |
|---|---|---|---|
| Phone (< 640 px) | 1,900 | 1.5 | Off |
| Tablet (< 1100 px) | 2,600 | 1.75 | On |
| Desktop | 3,600 | 2 | On |
On devices that report 4 or fewer CPU cores (navigator.hardwareConcurrency), every count drops to 70%. The animation looks almost identical; the phone stays cool.
const lowPower = (navigator.hardwareConcurrency || 8) <= 4
const k = lowPower ? 0.7 : 1
if (width < 640) return { dots: Math.round(1900 * k), dprCap: 1.5, mouse: false }Stop drawing when nobody is looking
The cheapest frame is the one you never draw. The engine stops its loop the moment the canvas leaves the viewport or the tab is hidden, and restarts when it comes back:
this.io = new IntersectionObserver(([entry]) => {
this.visible = entry.isIntersecting
if (this.visible) this.start()
else this.stop()
})
this.io.observe(canvas)
document.addEventListener('visibilitychange', this.onVisibility)It also boots late: the engine is created when the browser is idle, after the page is readable and interactive. I covered that boot order in How I Built anjay.dev with React 19 and Vite.
Accessible by design
A canvas is just pixels to a screen reader or a crawler. So the canvas is decoration (aria-hidden) and the real headline sits in the HTML above it. People who prefer reduced motion get a single composed frame instead of an animation, using matchMedia('(prefers-reduced-motion: reduce)'). The demo in this article does the same.
Mistakes that kill the frame rate
FAQ
Canvas 2D or WebGL for particle text?
Up to a few thousand particles, Canvas 2D is simpler and plenty fast if you follow the budget above. Past ten thousand, or with lighting and depth, WebGL wins. anjay.dev uses both: Canvas 2D for the hero text, WebGL for the denser fields on the work pages.
Could I do this with SVG or DOM elements?
Not at this scale. Thousands of DOM or SVG nodes each carry layout and style cost. A single canvas is one element, however many particles it draws.
How many particles should I use?
Fewer than you think. Text stays readable from around 800 dots on a phone. Tune by eye with the slider above, then scale by device like the tier table.
Quick checkpoint
Checkpoint · 3 questions
How does the animation know where the letters are?
The word is drawn once on a hidden canvas and its ink pixels are sampled into targets with getImageData.
What makes the word look hand-written instead of popping in?
The writing wave: left targets depart first, with a little random jitter for an organic feel.
Which change cuts per-frame cost the most?
Colour-batched drawing turns thousands of fillStyle switches per frame into a handful.