Skip to article

spring

spring() creates physics-based spring animations, configured by bounce, stiffness, damping, and mass.

The spring function is most often used to provide spring functionality to the mini animate() function.

import { animate } from "motion/mini"
import { spring } from "motion"

animate(
  element,
  { transform: "translateX(100px)" },
  { type: spring, bounce: 0.3, duration: 0.8 }
)

However, spring can also be used directly for low-level, advanced use cases. For instance, creating a spring visualiser.

Usage

Import spring from Motion.

import { spring } from "motion"

spring is a function that returns a generator.

const generator = spring({ keyframes: [0, 100] })

This generator can be used to sample to spring at specific times (defined in milliseconds).

As a generator, next() returns two values, value and done.

const { value, done } = generator.next(10) // Spring state at 10 milliseconds

The spring can be sampled in a non-linear fashion, meaning you can sample the spring at any time.

generator.next(100)
generator.next(10)

Sampling a spring

For most use-cases, like linear() easing generation or visualisation, you will probably want to run the generator in time order. You can do this with a normal loop that continues until the spring is done.

const generator = spring({ keyframes: [25, 75], stiffness: 400 })
const output = []

let isDone = false
let time = 0
const sampleDuration = 20 // ms

while (!isDone) {
  const { value, done } = generator.next(time)

  output.push(value)

  time += sampleDuration

  if (done) isDone = true
}