Skip to content

All posts Needler Auf Deutsch lesen

Drawing a haystack: 4,500 straws in a few dozen canvas strokes

How Needler's new hero draws a heap of straw on a canvas cheaply, buries a needle in it, animates without script and keeps a perfect desktop Lighthouse score.

JP 7 min read

Needler's landing page used to open on an animated ASCII globe. It looked good and it had cost me real work to make it fast, but it showed the wrong thing. Needler reads thousands of public posts a day and keeps the few where someone describes a problem worth solving: one needle, a lot of hay. The globe said "the whole world", and the five steps further down said five other things, because each was a different ASCII piece (a radar, falling sand, matrix rain, a bar chart and an owl).

So the globe went, along with the ascii.rest package, the vendored piece, its Web Worker, the poster image and the build alias that kept the package's 440 lazy chunks out of the bundle. In its place is a heap of straw drawn on a canvas, with a needle buried in it and a blue thread that runs from the needle up to the card with this week's free idea. The pointer pushes straw aside, a tap does the same on a phone, and loose straws keep drifting down onto the pile.

This post is about drawing that heap cheaply. An earlier version took 110 to 135 ms for a full draw with Chrome's CPU slowed down four times, the way Lighthouse tests phones. The current one takes 7 to 20 ms.

The heap is one function

Everything in the hero hangs off one curve: the height of the heap's surface at each x.

ts
top = (x) => h - base - peak * Math.exp(-(Math.abs((x - cx) / spread) ** 2.4));

An exponent of 2 would give a bell curve. 2.4 gives a rounder dome with flanks, which looks more like a stack. The centre cx and the height peak come from the needle: the component reads the needle SVG's position with getBoundingClientRect() and its geometry from a small object the needle component exports (view box, eye, angle, length and the thread as one cubic curve). The peak stands 150 px above the needle, scaled with it (with a floor of 120 px of height), so the needle lies deep in the straw whatever the layout does.

Straws are scattered by rejection sampling against that curve. A random point below the surface is kept with a probability that grows with its depth (0.15 + depth / 60), a point just above it is kept 2% of the time, and anything higher is dropped. Each straw lies along the local slope, about one in seven near the surface pokes out of it, and roughly one in eight points anywhere. Straws deeper in the heap get darker tones. The random numbers come from a small linear congruential generator with a fixed seed, so the heap is the same on every visit and every resize.

The straw count follows the heap's area, min(4500, w * (base + peak * 0.6) / 50), so a wide desktop hero gets the full 4,500 and a phone gets far fewer.

Thousands of straws, a few dozen strokes

The obvious version strokes every straw on its own: set the colour, set the width, stroke(), thousands of times per frame. Most of the cost there is the state changes and the stroke calls, not the geometry.

Straws don't need unique colours, though. Each one gets a style key with coarse steps: one of five tones, opacity rounded to tenths and width rounded to quarter pixels.

ts
const a = Math.max(1, Math.round(alpha * 10)) / 10;
const wd = Math.round(width * 4) / 4;
const key = `${+front}|${tone}|${a}|${wd}|${off}`;

Every straw with the same key goes into one Path2D as a quadratic curve, and each style is stroked once. The styles are sorted so shadows go first, then dim straw, then bright straw, then the thin lit edges that thicker straws get along their upper side. That's the whole drawing order, and a frame comes down to a few dozen stroke() calls.

A blur for free

Straw alone looks like a scribble; the gaps between straws need something behind them so the heap reads as one mass. That body is a gradient fill, from a lit brown at the top to near black at the bottom, and its edge should be soft. A filter: blur() on a canvas that size is expensive, so the body is drawn once into a second canvas at an eighth of the resolution and scaled up with drawImage and imageSmoothingQuality = 'high'. Upscaling smooths the edge, and the blur costs nothing.

One detail matters once only part of the canvas is redrawn: copying only the matching part of the small body would leave seams, because the scaled-up edges of neighbouring parts don't meet exactly. So every draw copies the whole body and lets a clip rectangle limit it to the dirty area.

Redraw only what moved

The pointer pushes straw within 90 px. Each animation frame, step() eases every pushed straw towards its target offset and returns the box around everything that moved, or null once it has all settled. The loop redraws the union of that box and the previous one (so straw that sprang back out of the area is cleared too), and stops requesting frames when nothing moves. With the pointer away from the heap, no script runs at all.

Two more limits keep the canvas cheap. The heap is only rebuilt when a key made of the hero's size and the needle's position changes, because fonts often finish loading without moving anything. And the canvas has at most about 2.5 million pixels: on a big desktop screen at 2x, a full-resolution canvas made pushing straw lag, because the browser composites the whole canvas every frame.

ts
const dpr = Math.min(devicePixelRatio || 1, 2, Math.sqrt(2_500_000 / (w * h)));

Buried, not lying on top

The needle is an SVG that sits above the back canvas, so on its own it would lie on the heap like a pin on a carpet. To bury it, a small second canvas sits above the content, sized to the needle plus the reach of the straws around it. It holds only the straw that crosses the needle: a segment intersection test picks up to seven of the heap's own straws that cross the middle 60% of the needle, adds three longer ones laid across it, and moves up to six more that cross the lower part of the thread so the thread goes into the heap instead of resting on it. Those straws get a faint shadow, offset by about a pixel, and the needle's eye and point stay in sight.

Motion without script

Apart from the pushing, nothing in the hero is animated by script. The heap drops into place once with a CSS animation of transform and opacity, and the falling straws are plain span elements whose start, end, rotation and opacity are CSS custom properties read by one shared @keyframes. The compositor moves them, and the heap is drawn once on load.

The five steps further down are now inline SVG scenes in the same visual language, also animated only with CSS: straw falling onto a heap, a sieve, a reading beam, straws lining up into a brief with six score bars, and the needle pulled out and ticked. In the reading scene, each straw has to light up exactly when the beam passes it. The beam's centre sweeps from x = -30 to 270 in 3.6 s, so each straw's animation delay is computed from its position:

ts
const hit = ((x + 30) / 300) * READ_S;

Only the scene of the active step is mounted, so one animates at a time. With prefers-reduced-motion: reduce, the base styles show a finished still of each scene, and the hero's heap appears without the drop or the falling straws and ignores the pointer. All animation lives inside a prefers-reduced-motion: no-preference block.

What Lighthouse said

Against a production build served locally with Wrangler, the desktop run scores 100 for performance, accessibility, best practices and SEO. The mobile run scores 100 on the last three, and performance landed between 86 and 97 across runs. The machine was busy (load average around 4.6) and the spread followed the load, so I wouldn't read more than "about the same as the globe in a worker" into it. The long tasks that remain are the first layout of the HTML, around 400 ms on the throttled CPU, and hydrating the landing page, not the heap.

Two fixes came out of the audit that had nothing to do with straw. A few grey labels at 50% and 55% black on white were too light, and are 60% now. And the counters at the top of the hero changed width while counting up, which shifted the text next to them. The fix renders the final value invisibly in the same grid cell, so the box has its final width from the first frame:

svelte
<span class="inline-grid text-right tabular-nums">
	<span class="invisible col-start-1 row-start-1" aria-hidden="true">{format(value)}</span>
	<span class="col-start-1 row-start-1">{format(counting ?? value)}</span>
</span>

One last thing I'd watch for in any canvas hero: reading document.fonts during hydration forced a layout of the whole page there. The heap asks for document.fonts.ready only after its first build, so a late font can still move the needle without the check landing in the middle of start-up.

The non-technical side of the redesign, written for founders working on their own landing page, is on Needler's blog: a landing page checklist from the same redesign.

#canvas #performance #svelte

About the project

Candidate 1 / 3 signals

Payout reconciliation for small SaaS

Strength 9 / 30

In development 2026

Needler

Find what to build before someone else does.

Building is easy now. Knowing what to build isn’t. Needler reads thousands of public developer conversations a day and turns the real problems people describe into scored software opportunities you can validate.

SvelteKit / Svelte 5 / Postgres + pgvector / Trigger.dev / Groq

Visit needler.by-jp.de

Keep reading

,8 min read

80 × 40 × 190 cm: which number is the depth?

How I'm testing with Nischler whether pages about cabinet sizes get Google traffic before there are any products. Demand check, parser and stop rules.

Nischler

,2 min read

The contract is the commit

How Promotler borrows git's model (snapshots, hashes, merges and signed tags) to make sponsored posts provable, without making marketers learn git.

Promotler