Shaders From Zero · Episode 08

Time, Easing & Animation in Shaders

Time, Easing & Animation in Shaders is Episode 08 of Shaders From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.

Part of the MasterAllArts Creative 3D Roadmap .

Episode 08 · Shaders From Zero · Season 1 Finale

We've been throwing sin(uTime) at things for seven episodes. This episode formalizes the animation vocabulary you've been using by feel — period and phase, easing curves, looping vs one-shot, staggered timings, and the first real interaction: making the shader respond to the mouse. By the end you have the toolkit Season 2 will build named effects out of.

This is the last episode of Season 1. Everything from "what is a shader" through GLSL essentials, UVs, noise, SDFs, color, and vertex displacement has been the grammar. Animation is the verb tense — how the grammar moves through time. Get this right and every effect in Season 2 will feel alive instead of "static thing with a rotation matrix slapped on it."

0 fps
ShaderMaterial · GLSL · uMouse
Linear sawtooth — fract(uTime * 0.3). Notice the snap at the loop.

The uTime pattern (a recap)

You've seen this since Episode 1, but here it is named and pinned down. Every shader that animates has two halves: a tiny JS side that pushes elapsed time into a uniform every frame, and a GLSL side that reads it.

// JS — once per frame, inside setAnimationLoop
material.uniforms.uTime.value = t * 0.001;  // t is ms; divide for seconds

// GLSL — declared once, read anywhere
uniform float uTime;
// ... and inside main() ...
float wobble = sin(uTime * 2.0);

That's the entire mechanism. uTime is just a number. It happens to be "seconds since the page loaded," but the shader doesn't know that and doesn't care. To the shader, uTime is "an ever-increasing float you can feed into any periodic function."

One thing that gets glossed over: uTime accumulates forever. After a few minutes of running, you're at t = 120.0 — still fine. After hours, single- precision floats start to lose accuracy and your sin(uTime) begins to jitter visibly. The fix is one line, applied defensively:

// JS
material.uniforms.uTime.value = (t * 0.001) % 1000.0;  // wrap before precision dies

Or do it shader-side with mod(uTime, 1000.0). For a typical tutorial demo that stays open for ten minutes you'll never notice, but if you ship a kiosk that runs for a week, you will. Worth knowing.

Sine cycles — period, amplitude, offset

Pure sin(uTime) oscillates between -1 and 1. That's the only thing the raw function does. To shape it into "I want this value to bounce between 0.2 and 0.8 every 4 seconds," you compose three transformations: period (how fast), amplitude (how far), offset (where centered).

  • sin(uTime) has a natural period of 2π — about 6.28 seconds.
  • To control period directly: sin(uTime * (2.0 * PI / period)) where period is in seconds.
  • Amplitude — just multiply the result. amp * sin(...) oscillates between -amp and +amp.
  • DC offset — just add. offset + amp * sin(...) oscillates around offset.

The general pattern, memorize it once:

float PI = 3.14159265;
float value = offset + amp * sin(2.0 * PI * uTime / period + phase);

Five knobs: offset, amp, period, phase, plus the implicit "where in time we are." That covers 90% of all shader oscillations you'll write. The other 10% needs easing, which is next.

Easing — sin is good, ease-in-out is better

A pure sine is symmetric. It lingers equally at every value, accelerating and decelerating in a perfectly smooth way that, ironically, often feels too smooth. Real animation lingers more at the extremes ("ease-in-out") or rushes through the middle ("ease-out"), the way a thrown ball does. The way a UI animation does. The way a falling object decelerates as it nears the ground.

These shapes have names — borrowed from CSS and Bezier curves. Here are the cubic family, in GLSL, copy-pasteable:

// Linear — no easing, baseline
float linear(float t) { return t; }

// Ease-in cubic — slow start, fast end
float easeInCubic(float t) { return t * t * t; }

// Ease-out cubic — fast start, slow end
float easeOutCubic(float t) { return 1.0 - pow(1.0 - t, 3.0); }

// Ease-in-out cubic — slow at both ends, fast through the middle
float easeInOutCubic(float t) {
  float a = 4.0 * t * t * t;
  float b = 1.0 - pow(-2.0 * t + 2.0, 3.0) / 2.0;
  return mix(a, b, step(0.5, t));
}

That last one — easeInOutCubic — is the workhorse. Any time something moves from A to B and you want it to feel intentional instead of mechanical, reach for it first.

Two style notes on the ease-in-out implementation. First: in pure CPU code you'd write a ternary — t < 0.5 ? a : b — and GLSL allows that. But step/mix is more idiomatic in shaders because it sidesteps the branching question entirely. Second: yes, both branches are evaluated regardless of which one is selected. That's a feature, not a bug — GPUs hate divergent branches inside a wavefront. The two extra multiplies are free.

The crucial rule: use easing on the animation parameter, not on uTime itself. This is the single most common easing mistake. The correct shape is:

float t01   = fract(uTime / period);       // 0..1, loops every `period` seconds
float eased = easeInOutCubic(t01);          // 0..1, eased
float x     = mix(0.1, 0.9, eased);          // 0.1..0.9, eased

If instead you write easeInOutCubic(uTime), the easing curve runs once as uTime passes through 0..1 — and then for the rest of eternity you're feeding it values like 47.3, where the function is meaningless. Easing is a 0-to-1 → 0-to-1 reshaping. You're responsible for getting the input into that range before you call it.

Looping vs one-shot

Two flavors of animation: ones that loop forever (idle, ambient, breathing, drifting), and ones that fire once when triggered (button press, hit, explosion, transition). The first kind is trivial in shaders. The second kind is harder.

Looping — the building blocks are fract and a couple of compositions:

// Sawtooth — 0 → 1 → snap back to 0, period seconds
float t = fract(uTime / period);

// Triangle wave — 0 → 1 → 0, period seconds
float t = abs(fract(uTime / period) * 2.0 - 1.0);

// Smooth bounce — apply easing on top of the triangle
float t = easeInOutCubic(abs(fract(uTime / period) * 2.0 - 1.0));

That triangle wave is worth committing to muscle memory. It's the "back and forth" loop. Pair it with an easing function and you have a swing, a pendulum, a knocking door — anything that goes there and back smoothly.

One-shot — trickier, because shaders are stateless. The shader doesn't remember "the button was pressed three seconds ago." So you stash the trigger time as a uniform from JS, and compute "time since trigger" inside the shader:

// JS — when the event happens
material.uniforms.uTriggerTime.value = currentTime;

// GLSL
uniform float uTime;
uniform float uTriggerTime;

void main() {
  float elapsed = uTime - uTriggerTime;       // seconds since trigger
  float t01     = clamp(elapsed / duration, 0.0, 1.0);
  float eased   = easeOutCubic(t01);
  // ... use `eased` to drive the effect ...
}

clamp(..., 0.0, 1.0) ensures the effect freezes at the end instead of running away into negative time before the first trigger or past completion after. This is the pattern behind ripples, hit-flashes, dissolve-on-spawn, and most "fire once" effects in shipped games.

Phase offsets — staggered animations

One of the cheap-but-powerful tricks in graphics: animate many things by the same formula, but offset each by a per-thing phase. The result feels like a coordinated dance — a wave traveling through a row of dots, leaves shimmering on a tree, fireflies blinking in sequence.

On a surface, the phase comes from UV. You've already been doing this since Episode 1:

float t = sin(uTime + vUv.x * 6.2832) * 0.5 + 0.5;

The vUv.x * 6.2832 is the phase. Pixels at vUv.x = 0 use phase 0; pixels at vUv.x = 0.5 use phase π. They're all on the same sine curve but reading different points along it, and the result is a wave traveling across the surface. Speed of the wave: how fast uTime advances relative to how far the phase spread is.

For discrete things — particles, instances, multiple objects in a loop — the phase comes from an index or position:

for (int i = 0; i < 5; i++) {
  float phase = float(i) * 0.6;          // staggered per-instance phase
  float y     = sin(uTime * 2.0 + phase);
  // ... draw the i-th thing at (x, y) ...
}

You'll see this in Stage 4 of the demo: five discs, identical formula, staggered phase. The eye reads the result as a wave, not as five independent animations. That perception is doing a lot of work for you, and it costs nothing.

Mouse — your first real input

So far every uniform we've used has been authored by the program. uTime comes from the clock. Colors come from JS constants. Nothing has come from the user. That changes now.

The cheapest, highest-impact interactive uniform is the mouse position. The recipe is three pieces: a JS listener that captures pointer position, a Vector2 uniform that carries it to the shader, and shader code that uses it.

// JS — module scope, shared across material rebuilds
const mouse = new THREE.Vector2(0.5, 0.5);

// In your shared uniforms factory — same Vector2 instance every time
uniforms: { uTime: { value: 0 }, uMouse: { value: mouse } };

// One listener, on the demo container, attached ONCE
mount.addEventListener("pointermove", (e) => {
  const rect = mount.getBoundingClientRect();
  mouse.set(
    (e.clientX - rect.left) / rect.width,
    1.0 - (e.clientY - rect.top) / rect.height,   // flip Y for shader convention
  );
});

Mouse position is now in [0,1] UV space — the same coordinate system your shader already speaks. That deliberate choice is what makes the rest easy. Comparing vUv and uMouse is direct:

// GLSL
uniform vec2 uMouse;
varying vec2 vUv;

void main() {
  float d = length(vUv - uMouse);          // distance from pixel to mouse
  vec3 col = mix(highlight, base, smoothstep(0.0, 0.3, d));
  gl_FragColor = vec4(col, 1.0);
}

That's it — that's an interactive shader. Pixels near the mouse glow; pixels far from it are the base color; smoothstep gives a soft falloff. Two lines of GLSL and the surface is responsive.

Smoothing the mouse over time

One subtle thing: the raw pointermove position is jittery. The cursor moves in discrete pixel jumps, and the resulting effect can feel snappy in a bad way. The fix is the same as you'd do for a "follower" in any UI — lerp toward the target every frame instead of jumping to it:

// JS — store two Vector2s, target and smoothed
const mouseTarget = new THREE.Vector2(0.5, 0.5);
const mouseSmooth = new THREE.Vector2(0.5, 0.5);

// Listener writes to target
mount.addEventListener("pointermove", (e) => { mouseTarget.set(...); });

// In the animation loop, smooth toward target before pushing to shader
mouseSmooth.x += (mouseTarget.x - mouseSmooth.x) * 0.1;
mouseSmooth.y += (mouseTarget.y - mouseSmooth.y) * 0.1;
material.uniforms.uMouse.value.copy(mouseSmooth);

The 0.1 is the "follow rate" — bigger numbers track tighter, smaller numbers feel laggier and more elegant. Try 0.05 for a luxurious follower; 0.3 for a snappy cursor highlight. The demo uses the un-smoothed version for clarity, but production interactive shaders almost always smooth.

Common first-day pitfalls

  • uTime precision drift. After many hours of runtime, single-precision floats lose enough resolution that sin(uTime) visibly jitters. Apply mod(uTime, 1000.0) defensively on the JS or GLSL side. You will not notice in development; you will get a bug report from someone who left a kiosk running all weekend.
  • Easing applied to uTime directly. If you write easeInOutCubic(uTime) the curve fires once, between t = 0 and t = 1, and after that you're sampling the function at values it was never designed for. Always normalize first: fract(uTime / period) or clamp(elapsed / duration, 0.0, 1.0).
  • Mouse position in screen pixels. Forgot to divide e.clientX by the canvas width, and now your shader is comparing vUv (in [0,1]) to a coordinate in the hundreds. Normalize to [0,1] and don't forget to flip Y — browser Y goes down, UV Y goes up.
  • Forgot to reattach the pointermove listener. Move the mouse, the shader doesn't respond, you spend twenty minutes confused. The fix is either: reattach the listener after every material rebuild, or (much better) keep one module-scope Vector2 and pass that instance to every material's uMouse uniform. The listener writes to the shared Vector2 once; every material reads the same one.
  • 60Hz vs 120Hz drift. If you animate by counting frames (uTime = frameCount * 0.016), your shader runs twice as fast on a 120Hz ProMotion display. If you animate by elapsed time (uTime = (performance.now() - start) * 0.001), it's framerate-independent. Always use elapsed time.
  • Mouse outside the canvas. pointermove on the canvas element fires only over the canvas. If you want the effect to keep working when the cursor leaves and re-enters, that's fine. If you want it tracked even when the cursor strays outside, listen on window and convert coordinates back into the canvas's local space.

Exercises

  1. Take Stage 2 (sine cycle) and chain easeInOutCubic onto it — but remember the rule. The sine output is in [-1, 1]; remap to [0, 1], ease, remap back if you want a signed value. Compare side by side with Stage 2 and Stage 3 — does eased-sine feel different from eased-triangle?
  2. Modify Stage 4 so the wave travels in both dimensions: have each disc's Y use sin(uTime + i * 0.6) as before, but also have its X drift slightly with cos(uTime * 0.5 + i * 0.6). The five discs should now describe a coordinated 2D motion.
  3. Add a second uniform uMouseSmooth alongside uMouse. Drive uMouse from the listener (raw target) and uMouseSmooth from a lerp in the animation loop. Render two discs — one at each — and feel the latency between input and follower. Tune the lerp constant until you find the rate you like.

What's next — Season 2: Real Effects

This is the end of Season 1. Eight episodes from "what is a shader" to "shaders that respond to your mouse with eased motion and staggered phases." You now have the full toolkit: vertex/fragment split, GLSL language, UVs, noise, SDFs, color, vertex displacement, time and easing.

Season 1 was the toolkit. Season 2 is what you build with it. Each episode in Season 2 is a single named effect that you'd ship in a real product — implemented from first principles using only the techniques you already know.

  • S2-01 Hologram — fresnel + scanlines + flicker. Sci-fi UI staple.
  • S2-02 Dissolve / Burn — noise threshold + discard. The classic "thing evaporates" effect.
  • S2-03 Water Surface — Gerstner waves on a plane + a faked reflection. Looks better than it has any right to.
  • S2-04 Glass & Refraction — refracted background, fresnel rim, chromatic aberration. The "expensive-looking material" recipe.
  • S2-05 Procedural Galaxy — polar coordinates, FBM, additive blend. Stars all the way down.
  • S2-06 Portal — animated swirl, edge glow, dimensional rift vibes. Heavy on phase offsets.
  • S2-07 Stylized Toon Shader — quantized lighting, ramp textures faked with step, hand-drawn rim. Anime in a fragment shader.
  • S2-08 Post-Processing Suite — render to texture, then run a second pass for bloom, chromatic aberration, vignette, grain. The final layer that makes everything look "shipped."

Same format as Season 1: long article, five demo stages, run it in your browser, no Webpack, no build step. Bring your toolkit.

Until then — go open Stage 5 of the demo, move your mouse around, and enjoy the payoff of seven episodes of buildup. That little disc following your cursor is the first shader in this whole series that responds to you. Everything you've learned is now an interactive medium.