Version: 4.0.0 Description: JavaScript Animation Engine Website: https://animejs.com GitHub: https://github.com/juliangarnier/anime
- Installation
- Getting Started
- Animation
- Timer
- Timeline
- Animatable
- Draggable
- Scope
- SVG Features
- Utilities
- Easings
- Web Animation API (WAAPI)
- Code Examples
Anime.js is available through multiple installation methods.
npm install animejsES Modules Import:
import { animate } from 'animejs';CommonJS Import:
const { animate } = require('animejs');ES Modules via CDN:
import { animate } from 'https://esm.sh/animejs';
// or
import { animate } from 'https://cdn.jsdelivr.net/npm/animejs';UMD Global Object:
<script src="https://cdn.jsdelivr.net/npm/animejs/dist/bundles/anime.umd.min.js"></script>
<script>
const { animate } = anime;
</script>Available distribution files from GitHub repository:
- ES modules:
dist/modules/index.jsand.cjs - Bundled formats:
anime.esm.js,anime.umd.js - Minified versions:
.min.jsvariants available
import { animate } from 'animejs';
animate('.square', {
translateX: 100,
scale: 2,
opacity: .5,
duration: 400,
delay: 250,
ease: 'out(3)',
loop: 3,
alternate: true,
autoplay: false,
onBegin: () => {},
onLoop: () => {},
onUpdate: () => {},
});import { animate, stagger, splitText } from 'animejs';
const { chars } = splitText('h2', { words: false, chars: true });
animate(chars, {
y: [
{ to: '-2.75rem', ease: 'outExpo', duration: 600 },
{ to: 0, ease: 'outBounce', duration: 800, delay: 100 }
],
rotate: { from: '-1turn', delay: 0 },
delay: stagger(50),
ease: 'inOutCirc',
loopDelay: 1000,
loop: true
});The animate() function creates animations.
Function Signature:
import { animate } from 'animejs';
const animation = animate(targets, parameters);Alternative Import:
import { animate } from 'animejs/animation';| Parameter | Accepts |
|---|---|
| targets | CSS selectors, DOM elements, JS objects, or arrays of targets |
| parameters | Object containing animatable properties, tween parameters, playback settings, and callbacks |
Return Value: Returns a JSAnimation object (or WAAPIAnimation for the lightweight WAAPI version).
Four main ways to specify targets:
- CSS Selector - Target elements using standard CSS selectors
animate('.square', { x: 100 });- DOM Elements - Direct references to DOM node objects
const element = document.querySelector('.square');
animate(element, { x: 100 });- JavaScript Objects - Plain JavaScript objects with animatable properties
const obj = { value: 0 };
animate(obj, { value: 100 });- Array of targets - Multiple targets animated simultaneously
animate(['.square', '.circle'], { x: 100 });Six categories of animatable properties:
- CSS Properties - Standard CSS styling properties
- CSS Transforms -
translateX,translateY,scale,rotate, etc. - CSS Variables - Custom CSS variables
- JavaScript Object Properties - Properties of plain JavaScript objects
- HTML Attributes - Standard HTML element attributes
- SVG Attributes - SVG-specific properties
Example:
animate('.square', {
translateX: 100,
scale: 2,
opacity: .5,
duration: 400,
});Tween Values Array:
animate('.square', {
x: [0, 100, 200],
y: [0, 100, 200],
duration: 3000,
})Tween Parameters Array:
animate('.square', {
x: [{to: 100}, {to: 200}],
y: [{to: 100}, {to: 200}],
duration: 3000,
})Duration Based (Array of Objects):
animate('.square', {
keyframes: [
{ x: 100, y: 100 },
{ x: 200, y: 200 },
],
duration: 3000,
})Percentage Based (Object with Time Keys):
animate('.square', {
keyframes: {
'0%' : { x: 0, y: 0 },
'50%' : { x: 100, y: 100 },
'100%': { x: 200, y: 200 },
},
duration: 3000,
})delay- Controls initial timing before animation startsduration- Specifies animation lengthloop- Enables repeating behavior (true for infinite, number for specific count)loopDelay- Sets pause between loop iterationsalternate- Reverses direction on each cyclereversed- Inverts playback directionautoplay- Begins automatically upon creationframeRate- Defines refresh rate (accepts boolean or numeric value)playbackRate- Adjusts playback speed
Execute functions at specific points during animation playback:
- onBegin - Triggers at animation start
- onComplete - Triggers when animation finishes
- onBeforeUpdate - Triggers before each update
- onUpdate - Triggers during animation updates
- onRender - Triggers on each render frame
- onLoop - Triggers when loop iteration completes
- onPause - Triggers when animation pauses
- then() - Promise-based callback method
Example:
animate('.square', {
x: 100,
onBegin: () => console.log('Animation started'),
onUpdate: (self) => console.log('Progress:', self.progress),
onComplete: () => console.log('Animation finished'),
});Available methods on Animation instances:
- play() - Start animation playback
- reverse() - Play animation backwards
- pause() - Halt animation without resetting
- restart() - Reset and restart from beginning
- alternate() - Toggle between forward/backward direction
- resume() - Continue from paused state
- complete() - Jump to animation end
- cancel() - Stop and remove animation
- revert() - Restore original element state
- reset() - Return to initial state
- seek() - Jump to specific time position
- stretch() - Extend animation duration
- refresh() - Recalculate animation values
Usage Pattern:
const animation = animate(target, parameters);
animation.play();
animation.pause();
animation.restart();The createTimer() function schedules and controls timed callbacks as an alternative to setTimeout() or setInterval(), keeping animations and callbacks synchronized.
From main module:
import { createTimer } from 'animejs';
const timer = createTimer(parameters);From subpath:
import { createTimer } from 'animejs/timer';Accepts an object containing Timer playback settings and Timer callbacks.
Return Value: Returns a Timer instance.
import { createTimer, utils } from 'animejs';
const [ $time, $count ] = utils.$('.value');
createTimer({
duration: 1000,
loop: true,
frameRate: 30,
onUpdate: self => $time.innerHTML = self.currentTime,
onLoop: self => $count.innerHTML = self._currentIteration
});Nine configuration options available:
- delay - Controls initial timing before timer starts
- duration - Specifies timer length
- loop - Enables repeating behavior
- loopDelay - Sets pause between loop iterations
- alternate - Reverses direction on each cycle
- reversed - Inverts playback direction
- autoplay - Begins automatically upon creation
- frameRate - Defines refresh rate (accepts boolean or numeric value)
- playbackRate - Adjusts playback speed
Configuration Example:
createTimer({
duration: 1000,
frameRate: true,
loop: true,
onBegin: () => {},
onLoop: () => {},
onUpdate: () => {},
});onBegin- Triggers at timer startonComplete- Triggers when timer finishesonUpdate- Triggers during timer updatesonLoop- Triggers when loop iteration completesonPause- Triggers when timer pausesthen()- Promise-based callback method
play()- Start timerreverse()- Play timer backwardspause()- Halt timerrestart()- Reset and restartalternate()- Toggle directionresume()- Continue from paused statecomplete()- Jump to endreset()- Return to initial statecancel()- Stop and cancel timerrevert()- Revert changesseek()- Jump to specific timestretch()- Adjust duration
currentTime- Current playback timeprogress- Animation progress (0-1)state- Current state of the timer- Related timing data
Timelines coordinate multiple animations and timers in sequence or parallel.
import { createTimeline } from 'animejs';
const timeline = createTimeline(parameters);Alternative Import:
import { createTimeline } from 'animejs/timeline';Adding Content:
add()- Adds animations or timers to the timelinesync()- Synchronizes WAAPI animations or other timelinescall()- Executes callback functions at specific positionslabel()- Creates named position markersset()- Sets property valuesremove()- Removes items from the timeline
Playback Control:
play(),pause(),resume(),reverse(),restart(),alternate()complete()- Jumps to the endcancel()- Stops and cancels animationreset()- Returns to initial staterevert()- Reverts property changesseek()- Moves to a specific time positionstretch()- Adjusts durationrefresh()- Recalculates valuesinit()- Initializes the timeline
Configure via parameters object:
defaults- Default animation settingsdelay,duration,loop,loopDelayalternate,reversed,autoplayframeRate,playbackRate,playbackEase
Timeline events include:
onBegin,onCompleteonBeforeUpdate,onUpdate,onRenderonLoop,onPausethen()
const tl = createTimeline({ defaults: { duration: 750 } });
tl.label('start')
.add('.square', { x: '15rem' }, 500)
.add('.circle', { x: '15rem' }, 'start')
.add('.triangle', { x: '15rem', rotate: '1turn' }, '<-=500');The createAnimatable() function creates instances designed to efficiently animate target properties, making it an ideal replacement for animate() and utils.set() in situations where values change frequently.
From main module:
import { createAnimatable } from 'animejs';From standalone subpath:
import { createAnimatable } from 'animejs/animatable';const animatable = createAnimatable(targets, parameters);| Parameter | Accepts |
|---|---|
targets |
CSS selectors, DOM elements, JS objects, or arrays |
parameters |
Object of Animatable settings |
An Animatable instance with property functions supporting both getters and setters:
animatable.propertyName(value, duration, ease); // Triggers animation
animatable.propertyName(); // Returns current valueImportant: Only Number or Array<Number> types are accepted for performance optimization.
const animatableSquare = createAnimatable('.square', {
x: 500, // x duration: 500ms
y: 500, // y duration: 500ms
ease: 'out(3)',
});
animatableSquare.x(x); // Animate x value
animatableSquare.y(y); // Animate y valueThe Draggable feature adds draggable capabilities to DOM Elements.
From main module:
import { createDraggable } from 'animejs';
const draggable = createDraggable(target, parameters);From subpath:
import { createDraggable } from 'animejs/draggable';createDraggable('.square');The createDraggable() function accepts:
- target: CSS Selector or DOM Element
- parameters (optional): Object containing axes parameters, settings, and callbacks
Axes Parameters:
x,y- Axis constraintssnap- Snap to valuesmodifier- Value transformationmapTo- Map drag to other properties
Settings:
trigger- Drag trigger elementcontainer- Constraint containercontainerPadding- Container paddingcontainerFriction- Container frictionreleaseContainerFriction- Release frictionreleaseMass- Release massreleaseStiffness- Release stiffnessreleaseDamping- Release dampingvelocityMultiplier- Velocity multiplierminVelocity- Minimum velocitymaxVelocity- Maximum velocityreleaseEase- Release easingdragSpeed- Drag speeddragThreshold- Drag thresholdscrollThreshold- Scroll thresholdscrollSpeed- Scroll speedcursor- Cursor style
Callbacks:
onGrab- Triggered when grabbedonDrag- Triggered during dragonUpdate- Triggered on updateonRelease- Triggered on releaseonSnap- Triggered on snaponSettle- Triggered when settledonResize- Triggered on resizeonAfterResize- Triggered after resize
disable()- Disable draggingenable()- Enable draggingsetX()- Set X positionsetY()- Set Y positionanimateInView()- Animate into viewscrollInView()- Scroll into viewstop()- Stop draggingreset()- Reset positionrevert()- Revert changesrefresh()- Refresh draggable
Returns a Draggable instance with full API access to properties and methods.
The Scope feature enables instances to react to media queries, use custom root elements, share default parameters, and be reverted in batch.
import { createScope } from 'animejs';
const scope = createScope(parameters);Alternative Import:
import { createScope } from 'animejs/scope';Accepts optional Scope parameters including:
mediaQueries- Define responsive breakpointsroot- Specify custom root elementdefaults- Share default animation settings
- add() - Add constructor function
- addOnce() - Add single-execution constructor
- keepTime() - Maintain animation timing
- revert() - Batch revert all animations
- refresh() - Refresh scope state
createScope({
mediaQueries: {
isSmall: '(max-width: 200px)',
reduceMotion: '(prefers-reduced-motion)',
}
})
.add(self => {
const { isSmall, reduceMotion } = self.matches;
if (isSmall) {
utils.set('.square', { scale: .5 });
}
animate('.square', {
x: isSmall ? 0 : ['-35vw', '35vw'],
duration: reduceMotion ? 0 : isSmall ? 750 : 1250
});
});The scope automatically reacts to media query changes and accessibility preferences.
Anime.js provides three primary SVG utility functions for advanced SVG animations.
From the svg object:
import { svg } from 'animejs';
svg.morphTo();
svg.createMotionPath();
svg.createDrawable();Directly from main module:
import { morphTo, createMotionPath, createDrawable } from 'animejs';From subpath:
import { morphTo, createMotionPath, createDrawable } from 'animejs/svg';- morphTo() - Enables morphing animations between SVG shapes
- createDrawable() - Creates drawable SVG elements for line-drawing animations
- createMotionPath() - Generates motion path animations along SVG paths
Anime.js provides extensive utility functions for DOM manipulation, random generation, mathematical operations, and animation helpers.
From utils object:
import { utils } from 'animejs';
utils.stagger();Direct imports:
import { stagger, $, get, set } from 'animejs';Subpath imports:
import { stagger, $ } from 'animejs/utils';Creates sequential effects by distributing values progressively across multiple targets.
Basic Syntax:
import { stagger } from 'animejs';
const functionValue = stagger(value, parameters);Parameters:
- value: Stagger value (numerical or range)
- parameters (optional): Configuration object
Return Value: Function-based value for use in animations
Usage Example:
import { animate, stagger } from 'animejs';
animate('.square', {
x: '17rem',
scale: stagger([1, .1]),
delay: stagger(100),
});Key Capabilities:
- Time Staggering - Distributes delays across sequential targets
- Values Staggering - Progressively assigns different values to each target
- Timeline Staggering - Controls position timing across multiple animations
Stagger Parameters:
start- Initial stagger pointfrom- Stagger direction originreversed- Reverses stagger orderease- Easing function for distributiongrid- 2D grid-based staggeringaxis- Grid axis specificationmodifier- Custom value transformationuse- Value application methodtotal- Total target count
$()- DOM selector utilityget()- Get property valuesset()- Set property valuescleanInlineStyles()- Remove inline stylesremove()- Remove elementssync()- Synchronize animationskeepTime()- Time keeper functionality
random()
Generates a random number within a specified range with optional decimal precision.
Signature:
const randomValue = utils.random(min, max, decimalLength);Parameters:
min(Number): Minimum valuemax(Number): Maximum valuedecimalLength(Number, optional): Decimal places (default: 0)
Returns: Number
Example:
import { utils } from 'animejs';
utils.set('.square', {
x: () => utils.random(2, 18, 2) + 'rem',
rotate: () => utils.random(0, 180),
scale: () => utils.random(.25, 1.5, 3),
});Other Random Utilities:
createSeededRandom()- Create seeded random generatorrandomPick()- Pick random itemsshuffle()- Shuffle arrays
round()- Round numbersclamp()- Constrain values within rangesnap()- Snap to valueswrap()- Wrap valuesmapRange()- Map value between rangeslerp()- Linear interpolationdamp()- Damping functionroundPad()- Round with paddingpadStart()- Pad string startpadEnd()- Pad string enddegToRad()- Convert degrees to radiansradToDeg()- Convert radians to degrees- Chain-able utilities - Functions supporting method chaining
Anime.js provides several easing function categories for controlling animation timing curves.
- Built-in eases - Pre-configured easing curves
- Cubic Bézier - Custom curve-based easing
- Linear - Constant rate of change
- Steps - Discrete step-based transitions
- Irregular - Custom non-standard easing patterns
- Spring - Physics-based spring animations
// From main module via easings object
import { easings } from 'animejs';
easings.eases.inOut(3);
// Direct imports from main module
import { eases, cubicBezier, spring } from 'animejs';
// Standalone subpath import
import { eases, cubicBezier, spring } from 'animejs/easings';Complete list of available easings:
| Type | Parameters | Variants |
|---|---|---|
| Linear | — | 'linear' |
| Power | power = 1.675 |
'in', 'out', 'inOut', 'outIn' |
| Quad | — | 'inQuad', 'outQuad', 'inOutQuad', 'outInQuad' |
| Cubic | — | 'inCubic', 'outCubic', 'inOutCubic', 'outInCubic' |
| Quart | — | 'inQuart', 'outQuart', 'inOutQuart', 'outInQuart' |
| Quint | — | 'inQuint', 'outQuint', 'inOutQuint', 'outInQuint' |
| Sine | — | 'inSine', 'outSine', 'inOutSine', 'outInSine' |
| Exponential | — | 'inExpo', 'outExpo', 'inOutExpo', 'outInExpo' |
| Circular | — | 'inCirc', 'outCirc', 'inOutCirc', 'outInCirc' |
| Bounce | — | 'inBounce', 'outBounce', 'inOutBounce', 'outInBounce' |
| Back | overshoot = 1.70158 |
'inBack', 'outBack', 'inOutBack', 'outInBack' |
| Elastic | amplitude = 1, period = .3 |
'inElastic', 'outElastic', 'inOutElastic', 'outInElastic' |
String notation:
animate(target, { x: 100, ease: 'outQuad' });
animate(target, { x: 100, ease: 'outElastic(.8, 1.2)' });Via eases object:
import { eases } from 'animejs';
eases.outQuad;
eases.outElastic(.8, 1.2);Code example:
import { animate, waapi } from 'animejs';
animate('.row:nth-child(1) .square', {
x: '17rem',
rotate: 360,
ease: 'inOut',
});
animate('.row:nth-child(2) .square', {
x: '17rem',
rotate: 360,
ease: 'inOut(3)',
});
waapi.animate('.row:nth-child(3) .square', {
x: '17rem',
rotate: 360,
ease: 'inOutExpo',
});Custom curve-based easing:
animate(target, { x: 100, ease: cubicBezier(.7, .1, .5, .9) });Parameters: Accepts four decimal control point values (x1, y1, x2, y2)
Physics-based spring animations with automatic duration calculation.
animate(target, { x: 100, ease: spring({ bounce: .35 }) });Uses Apple's SwiftUI spring model for visual feel:
-
bounce (Number): Range -1 to 1, default 0.5
- Values 0-1 create bouncy effects
- Negative values create over-damped curves
- Recommended range: -0.5 to 0.5
-
duration (Number): Perceived completion time in milliseconds
- Range: 10-10,000ms, default 628ms
- Represents when animation appears visually complete
For precise physics simulation:
-
mass (Number): Range 1-10,000, default 1
- Higher values increase inertia and slow motion
-
stiffness (Number): Range 0-10,000, default 100
- Higher values create tighter, faster-responding springs
-
damping (Number): Range 0-10,000, default 10
- Higher values reduce oscillation bounce
-
velocity (Number): Range -10,000 to 10,000, default 0
- Positive values provide initial momentum in target direction
A separate spring-level callback fires when perceived duration is reached, rather than actual settling completion. This synchronizes callback timing with visual completion.
A lightweight 3KB version exists: waapi.animate() for Web Animation API support, though with reduced features compared to the full Anime.js version.
import { waapi } from 'animejs';
waapi.animate('.square', {
x: '17rem',
rotate: 360,
ease: 'inOutExpo',
});- For simpler animations with hardware acceleration
- When file size is critical (3KB vs 10KB)
- For better performance on supported browsers
import { animate } from 'animejs';
animate('.square', {
translateX: 100,
scale: 2,
opacity: 0.5,
duration: 400,
delay: 250,
ease: 'out(3)',
loop: 3,
alternate: true
});import { animate } from 'animejs';
animate('.element', {
keyframes: [
{ translateX: 0, translateY: 0, scale: 1 },
{ translateX: 100, translateY: 0, scale: 1.2 },
{ translateX: 100, translateY: 100, scale: 1 },
{ translateX: 0, translateY: 100, scale: 0.8 },
{ translateX: 0, translateY: 0, scale: 1 }
],
duration: 2000,
ease: 'inOutQuad',
loop: true
});import { animate, stagger } from 'animejs';
animate('.grid-item', {
scale: [0, 1],
opacity: [0, 1],
translateY: [50, 0],
delay: stagger(100, { grid: [5, 5], from: 'center' }),
duration: 800,
ease: 'outExpo'
});import { createTimeline } from 'animejs';
const tl = createTimeline({
loop: true,
loopDelay: 500
});
tl.add('.box1', {
translateX: 250,
duration: 1000,
ease: 'outExpo'
})
.add('.box2', {
translateX: 250,
duration: 1000,
ease: 'outExpo'
}, '-=800') // Overlap by 800ms
.add('.box3', {
translateX: 250,
duration: 1000,
ease: 'outExpo'
}, '-=800');import { animate, spring } from 'animejs';
animate('.element', {
translateY: -100,
rotate: 360,
ease: spring({
bounce: 0.4,
duration: 800
})
});import { animate, stagger, splitText } from 'animejs';
const { chars } = splitText('h1', {
words: false,
chars: true
});
animate(chars, {
translateY: [-100, 0],
opacity: [0, 1],
delay: stagger(50),
duration: 800,
ease: 'outExpo'
});import { animate, stagger } from 'animejs';
// Grid-based stagger
animate('.square', {
scale: stagger([0.5, 1], {
grid: [5, 5],
from: 'center',
ease: 'outQuad'
}),
delay: stagger(100, {
grid: [5, 5],
from: 'center'
})
});import { animate, utils } from 'animejs';
utils.set('.square', {
x: () => utils.random(2, 18, 2) + 'rem',
rotate: () => utils.random(0, 180),
scale: () => utils.random(.25, 1.5, 3),
});import { createScope, animate, utils } from 'animejs';
createScope({
mediaQueries: {
isSmall: '(max-width: 200px)',
reduceMotion: '(prefers-reduced-motion)',
}
})
.add(self => {
const { isSmall, reduceMotion } = self.matches;
if (isSmall) {
utils.set('.square', { scale: .5 });
}
animate('.square', {
x: isSmall ? 0 : ['-35vw', '35vw'],
duration: reduceMotion ? 0 : isSmall ? 750 : 1250
});
});- CodePen Examples: Collection of live examples
- GitHub Repository: https://github.com/juliangarnier/anime
- Easing Editor Tool: Interactive easing function editor at https://animejs.com/easing-editor
- Migration Guide: Available on GitHub for upgrading from v3
- 4.0.0 - Current version with enhanced features
- 3.2.2 - Legacy version
- 2.1.0 - Legacy version
Documentation compiled from https://animejs.com/documentation/ - January 2026