spring() function creates physics-based spring animations that simulate real-world spring motion. It uses a spring solver adapted from Webkit’s implementation.
Basic Usage
Parameters
Thespring() function accepts a parameters object with the following properties:
Physical Properties
The mass of the spring. Higher values make the spring move more slowly. Clamped between 1 and 1000.
The stiffness of the spring. Higher values make the spring snap back more quickly. Clamped between a minimum value and 1000.
The damping force applied to the spring. Higher values reduce oscillation. Clamped between a minimum value and 1000.
The initial velocity of the spring. Clamped between -1000 and 1000.
Perceived Properties
The bounce percentage of the spring. Controls the amount of oscillation:
- Values ≥ 0: Critically damped to underdamped (creates bouncing)
- Values < 0: Overdamped (no bouncing)
The perceived duration of the spring animation in milliseconds. This represents how long the animation feels, not the actual settling time. Clamped between 10 (scaled by timeScale) and 10000.
Callback function called when the spring’s current time reaches the perceived duration. Receives the parent animation as an argument.
Usage Examples
Using Physical Properties
Using Perceived Properties
With Callback
How It Works
The spring solver calculates motion based on physics equations:- Underdamped (bounce ≥ 0): Creates oscillating motion with bouncing
- Critically damped (zeta = 1): Returns to rest position as quickly as possible without oscillating
- Overdamped (bounce < 0): Returns to rest slowly without oscillating
Perceived vs Physical Properties
You can control the spring using either:- Physical properties (
mass,stiffness,damping,velocity): Direct control over spring physics - Perceived properties (
bounce,duration): Higher-level controls that feel more intuitive
bounce or duration, the spring automatically calculates the appropriate physical properties using Apple’s SwiftUI spring duration implementation.
Spring Class
Thespring() function returns a Spring class instance with the following properties and methods:
Properties
mass: Get/set the massstiffness: Get/set the stiffnessdamping: Get/set the dampingvelocity: Get/set the velocitybounce: Get/set the bounceduration: Get/set the perceived durationease: The easing function used by the animation
Internal Properties
solverDuration: The actual duration calculated by the solversettlingDuration: The duration it takes for the spring to settlecompleted: Whether the spring has completed its perceived duration
Advanced Configuration
Notes
- The spring solver uses a time step of 0.02 for calculations
- Springs are considered at rest when the value is within 0.0005 of the target
- The maximum allowed spring duration is 60 seconds (60000ms)
- Setting physical properties will recalculate the perceived properties and vice versa