Most web animations are powered by time-based easing curves, but physical spring-based animation feels more dynamic and realistic. In this article, we’ll create a hand-rolled spring animation system in JavaScript, complete with mass, stiffness, and damping parameters—no external libraries required.
Why Spring-Based Animation?
Spring systems produce:
- More organic motion compared to cubic-bezier easing
- Realistic overshoot and rebound effects
- Adaptive performance based on frame rate
Step 1: Define the Spring Equation
This basic spring simulation uses Hooke’s Law with damping:
// Simple spring physics
function springStep({ x, v }, target, mass, stiffness, damping, dt) {
const F_spring = -stiffness * (x - target);
const F_damp = -damping * v;
const a = (F_spring + F_damp) / mass;
const newV = v + a * dt;
const newX = x + newV * dt;
return { x: newX, v: newV };
}
Step 2: Use requestAnimationFrame to Animate
We’ll run the simulation at every animation frame with a constant time step:
let state = { x: 0, v: 0 };
const target = 300;
const mass = 1;
const stiffness = 100;
const damping = 10;
const dt = 1 / 60;
const el = document.getElementById("ball");
function animate() {
state = springStep(state, target, mass, stiffness, damping, dt);
el.style.transform = translateX(${state.x}px)
;
if (Math.abs(state.v) > 0.01 || Math.abs(state.x - target) > 0.5) {
requestAnimationFrame(animate);
}
}
animate();
Step 3: Add Interactivity
Hook into mouse or UI events to dynamically change the target position:
window.addEventListener("click", (e) => {
state = { x: state.x, v: 0 }; // reset velocity
target = e.clientX;
animate();
});
Pros and Cons
✅ Pros
- More natural motion than cubic bezier easing
- Lightweight and fully customizable
- Works across browsers without dependencies
⚠️ Cons
- No built-in support for pausing, chaining, or staggering
- More math and tweaking than CSS transitions
- Edge cases may require clamping or advanced integration
🚀 Alternatives
- Framer Motion: React-based spring animations
- GSAP Physics Plugin: Robust for timelines and chained physics
- Popmotion: Library with declarative springs and decays
Summary
Spring physics can unlock a layer of realism that’s hard to match with basic CSS transitions. By simulating forces frame by frame, you gain full control over your animation’s feel—whether subtle or wildly bouncy. It’s perfect for snappy UIs, playful interactions, and kinetic typography.
If this was useful, you can support me here: buymeacoffee.com/hexshift
Top comments (0)