Custom GLSL Shaders in React: Turning Boring Images into Interactive Fluid
A photo on a web page just sits there. Put it on a canvas and run it through a shader, and it can bend, ripple and split into colours under the pointer like ink in water. I use effects like this on launch pages and portfolio heroes, and they’re a lot less code than most people expect. The demo below is one GLSL program of about 40 lines and a React component that mostly sets up the canvas and the sliders. No 3D library.
Move your pointer across it, then drag the sliders.
Uniforms · live
How a fragment shader thinks
Normal drawing code says “put this shape here”. A fragment shader works the other way around. The graphics card runs it once for every pixel of the canvas, all in parallel, and each run answers one question: what colour should this pixel be?
For an image effect, the answer is nearly always “the colour of the image at some other spot”. With no effect, each pixel reads the image at its own position and you get the photo back unchanged. Push that read position a little to the side and the image looks bent. Push it in a pattern of rings that spread out from the pointer, and you get ripples. That whole effect is the variable called offset in the shader below.
The shader
This is the exact code running in the demo, rendered from the same string the canvas compiles:
precision highp float;
uniform sampler2D uImage;
uniform float uTime;
uniform float uAspect; // canvas width / height
uniform float uAmp; // how far pixels get pushed
uniform float uFreq; // rings per unit of distance
uniform float uSpeed; // how fast the ring travels
uniform float uDecay; // how quickly a ripple dies
uniform float uChroma; // red/blue split
uniform vec3 uRipples[24]; // x, y, start time (-1 = unused)
varying vec2 vUv;
void main() {
vec2 offset = vec2(0.0);
float shine = 0.0;
for (int i = 0; i < 24; i++) {
vec3 r = uRipples[i];
float age = uTime - r.z;
if (r.z < 0.0 || age > 5.0) continue;
vec2 d = vUv - r.xy;
d.x *= uAspect; // keep the rings round
float dist = length(d);
float front = age * uSpeed; // radius of the travelling ring
float band = exp(-pow((dist - front) * 7.0, 2.0));
float life = exp(-uDecay * age);
float wave = sin((dist - front) * uFreq) * band * life;
offset += (d / max(dist, 0.0001)) * wave * uAmp;
shine += wave;
}
offset.x /= uAspect;
float r = texture2D(uImage, vUv + offset * (1.0 + uChroma)).r;
float g = texture2D(uImage, vUv + offset).g;
float b = texture2D(uImage, vUv + offset * (1.0 - uChroma)).b;
gl_FragColor = vec4(vec3(r, g, b) + shine * 0.12, 1.0);
}Taking it a piece at a time:
- The ripple list.
uRipplesholds the last 24 points where the pointer dropped a ripple: its position and the time it started. Old slots get reused, so the shader’s work stays fixed however much you move the mouse. - The travelling ring.
frontis how far the ring has spread (age × speed).bandis a Gaussian bump that’s 1 right on the ring and falls to 0 either side, so only a thin circle of pixels moves. - The wave.
sin((dist - front) * uFreq)makes the ring push pixels outward on one side and inward on the other, which reads as a ridge in water.lifefades it as it ages. - Round rings on a wide canvas. Texture coordinates run 0 to 1 in both directions, even on a wide image. Multiplying the x distance by the aspect ratio keeps the rings circular instead of oval.
- Colour split. The red, green and blue channels are read at slightly different offsets, scaled by
uChroma. That fringe is what makes it look like light through water rather than a warped JPEG.
Wiring it into React
The React side has one rule that matters more than anything else: nothing that changes every frame goes in state. A shader redraws 60 or more times a second. If the time or the pointer position lived in useState, the component would re-render at that rate and the page would stutter. Per-frame data lives in refs, and the draw loop reads them directly.
const uniforms = useRef({ amp: 0.03, freq: 40, speed: 0.35, decay: 1.4, chroma: 0.6 });
const ripples = useRef(new Float32Array(24 * 3).fill(-1));
useEffect(() => {
const gl = canvasRef.current.getContext('webgl');
const program = createProgram(gl, VERTEX_SHADER, FRAGMENT_SHADER);
loadTexture(gl, IMAGE);
let raf;
const frame = () => {
raf = requestAnimationFrame(frame);
gl.uniform1f(loc.time, performance.now() / 1000);
gl.uniform1f(loc.amp, uniforms.current.amp);
// …the other sliders
gl.uniform3fv(loc.ripples, ripples.current);
gl.drawArrays(gl.TRIANGLES, 0, 3); // one triangle covers the canvas
};
raf = requestAnimationFrame(frame);
return () => cancelAnimationFrame(raf);
}, []);The sliders are the one place state shows up. Each slider writes the new value into the ref, so the very next frame uses it, and into state, so the number next to the slider updates. React re-renders when you drag a slider, which is fine; it doesn’t re-render because time passed.
The pointer handler converts the mouse position into 0–1 coordinates (flipping y, because WebGL counts from the bottom) and drops a new ripple into the next slot. It only adds one if 45 milliseconds have passed and the pointer moved a little, otherwise a slow mouse would stack dozens of ripples on one spot.
Details that make it production-ready
- One triangle, not two. A single oversized triangle covers the whole canvas and avoids the seam two triangles leave along the diagonal. It’s a tiny saving, but it’s the standard trick for full-screen effects.
- Cap the pixel ratio at 2. A phone with a 3× screen would otherwise shade nine pixels for every CSS pixel. Nobody can see the difference past 2×.
- Stop when it’s off screen. An
IntersectionObserverpauses drawing when the canvas scrolls out of view. - Cross-origin images. WebGL refuses to read pixels from another domain unless that server allows it. Set
crossOrigin = 'anonymous'on the image and use a host that sends the right header, or serve the image yourself. - A real fallback. If the browser can’t create a WebGL context, the component renders the plain image with a caption. The page still makes sense.
- Clean up. Browsers allow only a handful of WebGL contexts at once. When the component unmounts it cancels the loop and releases the context, so moving between pages doesn’t leak them.
Accessibility
The canvas has role="img" and a label describing the picture and the effect, and the controls are ordinary range inputs, so they work with a keyboard and screen reader. The effect only moves when you move, and it settles within a few seconds, so it doesn’t run on its own for people sensitive to motion. If yours animates on its own, check prefers-reduced-motion and keep it still.
When to reach for a library instead
Plain WebGL is the right size for one flat effect on one image. Once you want 3D objects, a camera, lighting, post-processing or several effects layered together, three.js (or React Three Fiber, its React wrapper) saves far more time than it costs. The shader itself carries over almost unchanged; three.js will happily run your fragment shader on a plane.
WebGPU now ships in all the major browser engines, at least on some platforms, and its shading language (WGSL) is where new work is heading. For an effect like this, WebGL still runs on more devices, and the ideas move over directly: a program per pixel, a texture to read from, uniforms to steer it.
Things to try
- Push
uAmpto the top anduFreqdown low for slow, heavy swells. - Set
uDecaynear zero and the ripples keep crossing the image until their slots are reused. - Turn
uChromaup past 1.5 for a glitchy, prismatic look that suits music and fashion sites. - Swap the ripple math for
sin(vUv.y * 30.0 + uTime) * 0.01on the x offset and you have a heat-haze effect in one line.
Frequently Asked Questions
What is a GLSL shader?
GLSL is the programming language for small programs that run on the graphics card. A fragment shader runs once for every pixel on a canvas, in parallel, and decides that pixel’s colour. That is what makes per-pixel effects like ripples, distortion and colour splitting fast enough to run at 60 frames a second.
Do I need three.js or React Three Fiber to use shaders in React?
No. For a single flat effect on an image, plain WebGL takes a little over a hundred lines of setup and adds no dependencies to your bundle. three.js or React Three Fiber are worth it once you have 3D objects, cameras, lighting or several effects to manage.
What are shader uniforms?
Uniforms are values you pass from JavaScript into a shader, such as the time, the mouse position or a strength setting. They are the same for every pixel in a frame. Changing a uniform is how a React slider or a pointer event controls what the shader draws.
Do WebGL effects hurt page performance?
They can if they run all the time. Cap the pixel ratio at 2, stop drawing when the canvas is off screen, draw one triangle rather than a complex mesh, and keep per-frame values in refs instead of React state so components do not re-render 60 times a second.
Want a site that people play with?
I build interactive pieces like this for launches, portfolios and product pages, with fallbacks so they stay fast and accessible. Tell me what you have in mind.