WebGPU and Three.js Shaders in TSL: A Living Gradient, 4,500 Particles and a Hover Ripple
A shader is a stamp pressed on every pixel at once. Write it once in TSL, hand it to WebGPURenderer, and it runs on WebGPU or quietly on WebGL2. Read three effects from the sample project and the four habits that keep them light.
What you will learn
- Explain a shader as a tiny program run once per pixel, in parallel on the GPU
- Start a WebGPURenderer that falls back to WebGL2 and report which backend you got
- Read three TSL effects: a sin-warped gradient, instanced particles with per-dot easing, and a hover ripple with a colour split
- Keep shaders kind to the device: DPR cap, pause off screen, freeze for reduced motion
Before you start
- JavaScript basics
- Three.js: what it can do on real sites
This lesson is about effects that run on the graphics card: a living gradient, particles that follow the mouse, and a ripple when you hover an image, plus a fallback for browsers without WebGPU. We cover the foundations only. AI can generate shaders for you; you need to know what each one does so the code makes sense when your app grows.
What a shader is
Think of your screen as a floor of tiles. Each tile is one pixel, and a full HD screen has about two million of them. Now imagine a stamp. The stamp is the shader: a tiny program that runs once for every tile. You give it the tile's position, x and y, and it gives back a colour. Press it on every tile and the picture appears. The graphics card has thousands of small workers, so it stamps all the tiles at the same time. That's why shaders are fast.
Write once: WebGPU first, WebGL2 fallback
You write the shader in TSL, Three Shading Language, which looks like normal JavaScript. You hand it to the WebGPU renderer, and it picks the best backend for the browser: WebGPU where it's supported (the lecture names Chrome, Edge and Safari), otherwise it quietly falls back to WebGL2 and the same shader still works.
const renderer = new WebGPURenderer({ antialias: true, alpha: true })
renderer.setClearColor(0x000000, 0)
await renderer.init()
// ...
onBackend?.((renderer.backend as { isWebGPUBackend?: boolean }).isWebGPUBackend ? 'WebGPU' : 'WebGL2')
Create the renderer, await init(), and one more line tells you which backend you got. In the project, a small badge in the corner shows it.
Effect 1: a living gradient
The page background keeps moving. The shader is one function, the colour node, in effects/gradient.ts. Trimmed to its core:
material.colorNode = Fn(() => {
// centred, aspect-corrected coordinates
const p = uv().sub(0.5).mul(vec2(uAspect, 1)).mul(1.8).toVar()
// ... the pointer pushes the pattern away from itself ...
// domain warp: sin() of the coordinates, fed back into the coordinates, twice
const t = uTime.mul(0.1)
p.addAssign(vec2(sin(p.y.mul(2.1).add(t)), sin(p.x.mul(1.7).sub(t.mul(1.3)))).mul(0.5))
p.addAssign(vec2(sin(p.y.mul(3.3).sub(t.mul(0.8))), sin(p.x.mul(2.9).add(t))).mul(0.25))
// two flowing 0..1 "noise" fields
const n1 = sin(p.x.mul(2.0).add(sin(p.y.mul(2.5).add(t.mul(2))))).mul(0.5).add(0.5)
const n2 = sin(p.y.mul(3.0).add(sin(p.x.mul(2.0).sub(t.mul(1.5))))).mul(0.5).add(0.5)
// palette: ink -> violet -> magenta, with a rare warm highlight
const ink = color('#07061a')
const violet = color('#4a2bd0')
const magenta = color('#e0409a')
const amber = color('#ff9a5a')
const c = mix(ink, violet, smoothstep(0.15, 0.85, n1)).toVar()
c.assign(mix(c, magenta, smoothstep(0.55, 1.0, n2).mul(0.6)))
c.addAssign(amber.mul(pow(n1.mul(n2), 7).mul(0.7)))
// ... vignette, then return the colour
})()
Position in: take this pixel's position and centre it. sin bends the position so the pattern waves, and t, the time, keeps it moving. mix picks a colour between ink and violet (then magenta, with a touch of amber), and that's returned. Position in, sin to bend it, mix to pick a colour out.
Effect 2: particles that follow the mouse
Move the pointer left, then right, and a cloud of dots follows. In effects/particles.ts, COUNT is 4500, drawn with an InstancedMesh: one draw call for all of them. Each dot's soft glow is smoothstep on the length from its centre. The following part is plain JavaScript run every frame:
const k = dt * 60
for (let i = 0; i < COUNT; i++) {
const a = phase[i] + time * spin[i]
const r = radius[i] * scale * (0.7 + 0.3 * Math.sin(time * 0.7 + phase[i]))
const gx = tx + Math.cos(a) * r
const gy = ty + Math.sin(a) * r * 0.75
const e = Math.min(ease[i] * k, 1)
px[i] += (gx - px[i]) * e
py[i] += (gy - py[i]) * e
}
Each dot has its own ease, a lazy speed between 0.01 and 0.06. Every frame it moves that fraction of the way toward its goal near the pointer. Different speeds stretch the cloud into a trail. One draw call, every dot at its own pace.
Effect 3: a hover distortion
With the pointer away, the picture is calm. Put the pointer on the moon in the image, and rings spread out. From effects/hoverImage.ts:
const ripple = sin(dist.mul(34).sub(uTime.mul(4))) // outward travelling wave
const warp = dir.mul(ripple).mul(fall).mul(0.018).sub(d.div(squash).mul(fall).mul(0.14)) // ripple + lens bulge
// ...
const r = texture(tex, coverUv.add(warp).add(split)).r
const g = texture(tex, coverUv.add(warp)).g
const b = texture(tex, coverUv.add(warp).sub(split)).b
The first line makes the ripple, a sine wave travelling outward from the pointer. The second turns it into a warp, a small push on the picture's coordinates. Then the colour trick: read red, green and blue a little apart from each other. That small shift gives the rainbow edge.
One number, a new look
- Gradient: change the four colour values for a new palette, or the speed number.
- Particles: change
COUNT. Fewer dots for a calm look, more for a storm. - Hover: change the 34, and the rings get thinner or wider.
Small numbers, big changes. This is where AI is a great helper: describe the look, and it changes the numbers.
Shaders are fast; still be kind
From lib/stage.ts:
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)) // cap DPR at 2
// ...
// Do not burn GPU on a canvas that is scrolled out of view.
let visible = true
const io = new IntersectionObserver(([entry]) => { visible = entry.isIntersecting })
io.observe(host)
renderer.setAnimationLoop(now => {
if (!visible) { last = now; return }
const dt = prefersReducedMotion() ? 0 : Math.min((now - last) / 1000, 0.05)
// ...
})
- Fallback: no WebGPU, no problem; the same code runs on WebGL2.
- Cap the pixel ratio at 2 pixels per CSS pixel. A phone doesn't need more.
- Pause off screen: a canvas scrolled out of view stops drawing.
- Respect reduced motion:
dtbecomes 0, so time and the particles freeze.
And test on a phone, not just your laptop.
Try it yourself
Change the four gradient colours, set COUNT to 1000 and then 9000, and change the 34 in the ripple. The project files and sample prompts are in the community, free to join.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Backend vs Frontend: What Runs Where, and Why the Server Is the One You Trust
Every web app has two halves. The front end runs on the user's device and is trusted with nothing; the back end holds the data, the secrets and the rules. Checked with real requests to a Django blog.
One Request, Two Answers: the Same Post as an HTML Page and as JSON
Ask a Django blog for the same post twice: once as a 12,731-byte HTML page built by a template, once as 2,976 bytes of JSON built by a serializer. Compare the headers, see who builds the page, and why the server still owns every write.
A Blog Design from a Prompt: Downloading Figma Make Code and Reading App.tsx and BlogCard.tsx
Make a blog design from a prompt in Figma Make, download src.zip, unzip it with Python's zipfile module, and read the two files that matter: App.tsx with its selectedPost state and BlogCard.tsx with its props.
How a Web Page Works: HTML Tags, Elements and Attributes
A web page is a text file full of labelled pieces. Learn tags, attributes and nesting with three tiny pages, and see what breaks when an attribute or a closing tag is wrong.
