Spring Physics Explained: Damped Harmonic Oscillators in UI and WebGL
Deriving critically damped spring equations from second-order ODEs and implementing frame-rate-independent motion in TypeScript.
Duration-based easing curves (cubic-bezier) look great until a user interrupts an animation mid-flight—flicking a cursor ribbon or releasing a dragged card with velocity. A spring never restarts from zero; it preserves momentum continuously because its state is governed by a second-order ordinary differential equation.
The Damped Harmonic Oscillator
For displacement from a target , stiffness , damping , and mass :
Dividing by introduces the natural angular frequency and the damping ratio :
- Underdamped (): Overshoots the target and oscillates before settling.
- Critically damped (): Reaches equilibrium in minimum time without oscillation.
- Overdamped (): Approaches slowly without overshoot.
Frame-Rate-Independent Integration
Running raw x += vx per requestAnimationFrame callback breaks on 120Hz vs. 60Hz displays. Using a fixed physics timestep with an accumulator (the pattern used in this portfolio's cursor trail) guarantees identical motion across refresh rates.
export interface SpringState {
value: number;
velocity: number;
}
export function stepSpring(
state: SpringState,
target: number,
dtSeconds: number,
stiffness = 380,
damping = 32,
mass = 0.4,
): SpringState {
const displacement = state.value - target;
const springForce = -stiffness * displacement;
const dampingForce = -damping * state.velocity;
const acceleration = (springForce + dampingForce) / mass;
// Semi-implicit Euler: update velocity first, then position
const nextVelocity = state.velocity + acceleration * dtSeconds;
const nextValue = state.value + nextVelocity * dtSeconds;
return {
value: nextValue,
velocity: nextVelocity,
};
}Settling Without Infinite Loops
A pure spring decays asymptotically and never hits zero exactly. To avoid burning battery in an idle requestAnimationFrame loop, check both displacement and velocity against an epsilon threshold:
const settled =
Math.abs(target - state.value) < 0.15 &&
Math.abs(state.velocity) < 0.15;Once settled, snap value = target, zero velocity, and stop scheduling animation frames until the next pointer or scroll event wakes the loop.
Reactions & Discussion
Technical Dispatches
RSS Feed ↗