A canvas particle background that floats, dodges the mouse and slowly gathers into a shape you pass in as an SVG. One custom element, no libraries, and it respects reduced motion.

The case-study pages on my portfolio had a flat, empty hero. I wanted something alive behind the text, but not a video, not a WebGL scene and not another dependency. What I wanted was small: particles that drift around, move away from the cursor, and gather into a shape when you hover the area. The shape should be whatever SVG I hand it.

So I built <b55-particle-field>. One custom element, one JS file, one CSS file.

Live demo: bada55.eu/work/psyche. Hover the hero to make the particles form the BADA55 star, and move the mouse to push them around.

<div style="position: relative; isolation: isolate"> <b55-particle-field shape="/assets/work/particles-asterisk.svg" mode="both" count="1000" shape-align="left"> </b55-particle-field> <h1>Content stays above the field</h1> </div> 

Here is how it works, in the order I'd build it again.

1. One canvas, one loop, no pairwise maths

Every particle only knows about itself, its target and the cursor. There's no particle-to-particle interaction, so the cost per frame grows linearly with the count. I measured the CPU time of one frame (update plus draw) in a browser:

Particles ms per frame
182 0.08
728 0.18
2,912 0.44

A 60 fps frame has about 16 ms. Even three thousand particles use a few percent of it. (This is CPU time only. I haven't profiled compositing on a low-end phone, so check yours.)

Drawing is cheap for a second reason: particles are batched into one path per palette colour, so a frame is four fill() calls, not a thousand.

this.colours.forEach((colour, i) => { ctx.fillStyle = colour ctx.beginPath() for (const p of this.particles) { if (p.c % this.colours.length !== i) continue ctx.moveTo(p.x + p.r, p.y) ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2) } ctx.fill() }) 

The moveTo before each arc matters. Without it, the path draws a line from the end of one circle to the start of the next.

2. Two behaviours, one spring

A particle is always pulled toward a target. What changes is which target:

  • Floating: a slow wandering force that wraps at the edges. No fixed target.
  • Formed: a point sampled from the shape, and a soft spring that pulls the particle there.
if (form) { p.vx += (p.tx - p.x) * SPRING // 0.016: slow and soft p.vy += (p.ty - p.y) * SPRING p.vx *= DAMPING // 0.9 p.vy *= DAMPING } 

The low spring constant is what makes the formation feel slow instead of snapping into place. I started at 0.045 and it looked like a transition. At 0.016 it looks like something settling.

The cursor adds a repulsion on top, with a quadratic falloff so the edge of the effect is gentle. When the shape is formed, the push is scaled to 30% and the radius to 60%, so the cursor nudges the shape instead of destroying it.

3. The mode attribute

Instead of three components, one attribute:

mode Behaviour
drift Float and dodge the cursor. This is the default when there's no shape.
shape Always form the shape.
both Float. Form the shape while the cursor is over the area. Float again when it leaves.

The field has pointer-events: none, so it can sit behind links and buttons. That means it can't use mouseenter. Instead it listens for pointermove on window and checks whether the pointer is inside its own rectangle:

this.onMove = e => { const r = this.getBoundingClientRect() const inside = e.clientX >= r.left && e.clientX <= r.right && e.clientY >= r.top && e.clientY <= r.bottom this.mouse.inside = inside this.mouse.x = inside ? e.clientX - r.left : -9999 this.mouse.y = inside ? e.clientY - r.top : -9999 } 

Moving the cursor far outside parks it at -9999, so the repulsion maths simply finds nothing in range. No special case.

4. Turning an SVG into points

This is the part that makes the component reusable. The shape attribute takes either a path d string or the URL of an SVG file. I load it into an off-screen SVG, then sample points inside the shape:

const box = svg.getBBox() while (out.length < total && tries++ < total * 60) { const pt = svg.createSVGPoint() pt.x = box.x + Math.random() * box.width pt.y = box.y + Math.random() * box.height if (nodes.some(n => n.isPointInFill(pt.matrixTransform(n.getCTM().inverse())))) out.push(normalise(pt.x, pt.y)) } 

It's rejection sampling: throw darts at the bounding box and keep the ones that land inside. isPointInFill does the geometry for me, for paths, circles, rects, polygons, all of them.

Two details cost me time:

  1. isPointInFill ignores transforms. My test asterisk is one bar rotated three times with transform="rotate(...)". The first version drew only the vertical bar. The point has to be mapped through the inverse of each element's matrix (getCTM().inverse()) before the test. Outline sampling needs the opposite: getPointAtLength(...) and then matrixTransform(n.getCTM()).
  2. Open paths have no fill. A line drawing gives you zero hits. If fewer than a quarter of the requested points land inside, the component falls back to sampling the outline with getPointAtLength. You can also ask for it directly with sample="outline".

Points are normalised to −0.5…0.5 on the shape's longer side. Then shape-scale and shape-align (left, center or right) decide where it lands and how big it is. The same SVG works at any size.

5. Four colours that work on both themes

Particles pick one of four colours at random: lime, blue, orange and purple, the same clay palette as the rest of my design system. They're CSS custom properties, so the theme decides:

:root { --b55-particle-1: #8fae22; --b55-particle-2: #4a82a6; --b55-particle-3: #cf7424; --b55-particle-4: #7058c2; } :root[data-theme="dark"] { --b55-particle-1: #bada55; --b55-particle-2: #9cc9e2; --b55-particle-3: #f4ad6c; --b55-particle-4: #a996e6; } 

On the light theme the colours are a notch darker so they hold against a pale background. On dark they're the lighter tones. A canvas doesn't know about CSS, so the component reads the four properties with getComputedStyle and re-reads them every ~90 frames. That's how a theme toggle repaints the field without any event wiring.

Accessibility and manners

A decorative canvas has to behave:

  • aria-hidden="true" and no focusable content. It's purely decorative, and the meaning has to live in the text next to it.
  • prefers-reduced-motion: nothing animates. It draws one still frame, with the finished shape if there is one, and ignores the cursor.
  • Off-screen and hidden tabs: an IntersectionObserver and the Page Visibility API stop the loop, so it costs nothing when nobody's looking.
  • pointer-events: none: links and buttons above it keep working.
  • Touch screens: there's no hover, so particles just float. A tap or drag inside the area still counts as the cursor being over it.
  • Density: particles are semi-transparent, and the count scales down with the area. Keep it sparse behind small text.

Gotchas I hit

  1. Give the parent position: relative; isolation: isolate. The field is absolutely positioned with z-index: -1. Without isolate, it falls behind the page background instead of behind its section.
  2. Resize with ResizeObserver, not window.resize. The field's size depends on its parent, not on the window.
  3. Cap the pixel ratio at 2. A phone at 3× makes a canvas nine times the size for no visible gain on small dots.
  4. Keep particles when the count changes. On a resize or an attribute change I rebuild the particle list but keep each particle's position and velocity, so nothing teleports.
  5. Content JSON is read once. In my Eleventy setup the per-case count, align and scale come from a JSON file that is only read at server start, so I restart the dev server after changing it. It cost me a few confused minutes.
  6. Headless screenshots need a trick. For the cover image of this article I rendered the component in headless Chrome. Virtual time doesn't advance requestAnimationFrame the way a real browser does, so the particles never settled. Running with --force-prefers-reduced-motion makes the component draw its finished still frame, which is exactly what I wanted.

The parameters

Attribute Default What it does
mode both with a shape, else drift drift, shape or both
shape none Path d string, or the URL of an SVG on the same site
sample fill fill the inside, or trace the outline
shape-align center left, center or right
shape-scale 1 Size of the shape
count 380 Particles at desktop size
size 1 Particle size multiplier
repel-radius 110 Cursor push distance in px

Wrap-up

The idea underneath is small: a shape is just a bag of points, and a particle is just a point that wants to be somewhere. Sample the SVG once, give each particle a target, and let a weak spring do the animation. Everything else, the modes, the colours, the reduced-motion frame, is a few lines each.

It works with any SVG. A client's logo on their case study, a product outline, a letter. Pick something bold, because fine detail disappears at a few hundred particles.

The component is part of the BADA55 design system: b55-particle-field is one JS file plus one CSS file, and it needs nothing else.