How it works
A wave equation in two textures
This is a flagged, experimental effect, and the only one in the library that needs WebGL. Everything else here is CSS and SVG filters, which can't keep state from one frame to the next. Water ripples need exactly that: the surface now depends on the surface a moment ago.
1. The height field
The water is a grid of cells, each with a height and a vertical velocity, stored in the red and green channels of a float texture. One simulation step pulls every cell towards the weighted average of its eight neighbors, damps the velocity and moves the height:
#version 300 es
precision highp float;
uniform sampler2D uState;
uniform float uDamping;
out vec4 outState;
void main() {
ivec2 size = textureSize(uState, 0);
ivec2 c = ivec2(gl_FragCoord.xy);
ivec2 hi = size - 1;
vec4 s = texelFetch(uState, c, 0);
#define H(dx, dy) texelFetch(uState, clamp(c + ivec2(dx, dy), ivec2(0), hi), 0).r
// 9-point average: edges weigh 0.2, corners 0.05. Rings stay round; a plain 4-neighbor
// average spreads faster along the axes and turns them into rounded squares.
float avg = 0.2 * (H(1, 0) + H(-1, 0) + H(0, 1) + H(0, -1)) +
0.05 * (H(1, 1) + H(-1, 1) + H(1, -1) + H(-1, -1));
// Gain 1 keeps the wave speed at √0.3 ≈ 0.55 cells per step, slow enough for the grid to resolve
// the wavefront in every direction (at 2 the rings come out squarish).
s.g += avg - s.r;
s.g *= uDamping;
s.r += s.g;
outState = s;
} avg − height is a discrete Laplacian, the curvature of the surface, so this is
the wave equation, integrated one step at a time. A bump spreads out as a ring; the edges of
the grid read clamped coordinates, which acts like a wall and reflects the waves back. With Damping at 0.985, a ripple takes about 458 steps to fade to
a thousandth of its height; after that many steps without a new drop (and with no rain) the animation
loop stops by itself.
2. Ping-pong framebuffers
A shader can't read and write the same texture in one pass. So there are two: each step reads state A and renders the new state into B through a framebuffer, then the two swap roles. A drop is the same kind of pass with a different shader, which adds a smooth cosine bump around a point:
#version 300 es
precision highp float;
uniform sampler2D uState;
uniform vec2 uCenter;
uniform float uRadius;
uniform float uStrength;
out vec4 outState;
const float PI = 3.141592653589793;
void main() {
vec2 size = vec2(textureSize(uState, 0));
vec4 s = texelFetch(uState, ivec2(gl_FragCoord.xy), 0);
float d = length(gl_FragCoord.xy - uCenter * size) / max(uRadius, 1.0);
float bump = max(0.0, 1.0 - d);
s.r += (0.5 - 0.5 * cos(bump * PI)) * uStrength;
outState = s;
} // ping-pong: read state A, write state B, swap
function pass(program, uniforms) {
gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffers[1 - current]);
gl.viewport(0, 0, sim.width, sim.height);
gl.useProgram(program);
gl.bindTexture(gl.TEXTURE_2D, textures[current]);
uniforms();
gl.drawArrays(gl.TRIANGLES, 0, 3); // one triangle covers the target
current = 1 - current;
}
function frame(now) {
for (const d of drops.splice(0)) pass(dropProgram, () => setDrop(d));
for (let i = 0; i < steps; i++) pass(updateProgram, () => setDamping(damping));
render(); // to the canvas: refract the image through the surface
if (!settled) requestAnimationFrame(frame);
} The clock is fixed: every 1/60 s runs Steps per frame steps, whatever the display's refresh rate, so waves travel at the same speed on 60 and 120 Hz screens. Waves move about half a cell per step, which is why a coarser grid (lower Grid resolution) also makes them faster and wider. The grid is capped at 512 cells on the long side.
3. Refraction and glint
The last pass draws to the canvas. The surface normal comes from the height differences between neighboring cells. The image is sampled with an offset along the normal, which is refraction in the loosest sense (no depth, no Snell's law, but the eye doesn't mind), then mixed with the water color. A Phong term adds a sun glint where a slope mirrors the light towards the viewer.
#version 300 es
precision highp float;
in vec2 vUv;
uniform sampler2D uState;
uniform sampler2D uImage;
uniform vec2 uRefraction;
uniform float uSpecular;
uniform vec3 uTint;
uniform float uTintAmount;
out vec4 outColor;
void main() {
vec2 t = 1.0 / vec2(textureSize(uState, 0));
float hl = texture(uState, vUv - vec2(t.x, 0.0)).r;
float hr = texture(uState, vUv + vec2(t.x, 0.0)).r;
float hd = texture(uState, vUv - vec2(0.0, t.y)).r;
float hu = texture(uState, vUv + vec2(0.0, t.y)).r;
vec3 n = normalize(vec3(hl - hr, hd - hu, 0.08));
vec3 color = texture(uImage, clamp(vUv + n.xy * uRefraction, 0.0, 1.0)).rgb;
color = mix(color, uTint, uTintAmount);
vec3 light = normalize(vec3(-0.45, 0.6, 1.0));
float spec = pow(max(dot(reflect(-light, n), vec3(0.0, 0.0, 1.0)), 0.0), 80.0);
color += spec * uSpecular;
outColor = vec4(color, 1.0);
} WebGL can't read the page, so the water can only bend an image it has been given: src, or a procedurally drawn pool floor. The landscape option is the SVG
illustration from the duotone page, serialized into a Blob URL and rasterized. HTML on top (the
card) is not refracted; it stays real, selectable text.
4. Being a good citizen
const gl = canvas.getContext('webgl2', { alpha: false, antialias: false, depth: false });
// float render targets are an extension even in WebGL2
gl.getExtension('EXT_color_buffer_float') ?? gl.getExtension('EXT_color_buffer_half_float');
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA16F, w, h, 0, gl.RGBA, gl.HALF_FLOAT, null);
canvas.addEventListener('webglcontextlost', (e) => {
e.preventDefault(); // "I can restore": without it, no restored event
stopLoop(); showStillImage();
});
canvas.addEventListener('webglcontextrestored', () => createEverythingAgain()); - Context loss. The GPU process can drop a context at any time (driver
reset, too many contexts, a laptop switching GPUs). The component calls
preventDefault()onwebglcontextlost, shows the still image and rebuilds every program and texture onwebglcontextrestored. Try Simulate context loss, which usesWEBGL_lose_context. - Pixel ratio cap. The render pass runs once per device pixel; on a 3× phone that is nine times the pixels of 1×. Max pixel ratio (2 by default) caps the canvas backing store; the simulation grid has its own, lower resolution.
- When it runs. Only on screen (IntersectionObserver), in a visible tab,
and not under
prefers-reduced-motion: reduce, withpaused, or inside adata-motion="paused"region. A JavaScript loop isn't paused by the CSS rule that stops the other effects, so the component looks for a paused ancestor itself and watches the attribute. Under reduced motion it renders one still frame of flat water. - Cleanup. On destroy it deletes its textures, framebuffers and programs
and releases the context with
WEBGL_lose_contextinstead of waiting for garbage collection: browsers keep only a limited number of live contexts per page (often 16) and drop the oldest. - Interaction. The canvas is decorative and
aria-hidden. Pointer drops are a toy; Drop a stone does the same from the keyboard, and Rain moves the water without any input.
Browser support and performance
- WebGL2 is Baseline widely available (web-features,
webstatus.dev/features/webgl2), but rendering into float textures still needs
EXT_color_buffer_floatorEXT_color_buffer_half_float. Both are common; where neither exists, where WebGL2 is blocklisted, or with hardware acceleration off, the component shows the still image. Half-float (RGBA16F) textures are filterable in core WebGL2, which the render pass uses to smooth the coarse grid. - Checked in Chromium, including headless with SwiftShader (a software GPU). Firefox and Safari are untested.
- Per frame: two to eight simulation passes over at most 512 × 512 cells and one render pass over the canvas. Cheap for a GPU, but it keeps the GPU awake, which is why the loop stops as soon as the water is still and rain is off.
- This is a deliberately small, dependency-free WebGL2 example. For anything bigger (3D water, real caustics, fluid dynamics), use a WebGL library or WebGPU, which is not Baseline yet.