Skip to content

spring

Simulates a damped spring going from 0 to 1, the curve behind “spring” transitions of design tools, and computes how long it takes to settle.

The motion is solved exactly (under-, critically or over-damped), not by stepping a simulation, so at can be called at any time, in any order.

Available since v3.1.5

import { spring } from '@helpers4/animation';
// or, from the all-in-one package (same code, one install):
import { spring } from 'helpers4/animation';
spring(options: SpringOptions): Spring
ParameterTypeDescription
optionsSpringOptionsMass, stiffness, damping, initial velocity — see SpringOptions

Spring — A Spring

The duration comes from the physics: play it for durationMs.

const bouncy = spring({ stiffness: 300, damping: 15 });
bouncy.durationMs // => about 900
bouncy.at(bouncy.durationMs) // => 1

at() takes the elapsed time in milliseconds.

const s = spring();
const start = performance.now();
requestAnimationFrame(function frame(now) {
  draw(s.at(now - start));
  if (now - start < s.durationMs) requestAnimationFrame(frame);
});

A spring animation from 0 to 1, created by spring.

interface Spring {
  durationMs: number;
  at(timeMs: number): number;
  easing(t: number): number;
}

Physical parameters of a spring, as design tools (Figma, Framer, …) expose them.

interface SpringOptions {
  damping?: number;
  initialVelocity?: number;
  mass?: number;
  stiffness?: number;
}

View source on GitHub