Lightweight & Versatile JavaScript Animation Engine – Anime.js

Category: Animation , Javascript , Recommended | April 24, 2025
Author:juliangarnier
Views Total:3,567 views
Official Page:Go to website
Last Update:April 24, 2025
License:MIT

Preview:

Lightweight & Versatile JavaScript Animation Engine – Anime.js

Description:

Anime.js is a JavaScript animation engine that provides a single API to animate almost anything on the web – CSS properties, SVG paths, DOM attributes, even plain JavaScript Objects.

You can use it for subtle UI flourishes, complex SVG morphing, intricate sequence choreography via its timeline, or even synchronizing animations to scroll position.

Highlights:

  • Universal Targeting: Works with CSS selectors, DOM elements, NodeLists, Arrays, and plain JS Objects.
  • Modular API: Import only the parts you need (animate, timeline, stagger, etc.) to keep bundle size down.
  • Enhanced Transforms: Animate individual CSS transforms (translateX, rotate, scale) without conflicts. Function-based values add dynamic control.
  • SVG Toolkit: Built-in helpers for shape morphing, line drawing (stroke-dashoffset tricks made easy), and motion path animations.
  • Scroll Observer: Trigger and sync animations based on scroll position with various modes and callbacks.
  • Advanced Staggering: Easily create offset animations across multiple targets based on time, values, or timeline position.
  • Springs & Draggable: Built-in physics-based springs and a full Draggable API for interactive elements.
  • Timeline Control: Orchestrate complex sequences of animations and callbacks with precision timing.
  • Responsive Animations: Use the Scope API to adjust animations based on media queries.
  • Free & Open Source: MIT licensed, supported by sponsors.

See It In Action:

Installation:

You have several options for adding Anime.js to your project:

Using NPM:

npm install animejs

Then import Anime.js methods as ES6 modules:

import { animate } from 'animejs';

Using a CDN:

ES6 Modules:

<script type="module">
  import { animate } from 'https://cdn.jsdelivr.net/npm/animejs@VERSION/+esm';
</script>

Global object:

<script src="https://cdn.jsdelivr.net/npm/animejs@VERSION/lib/anime.iife.min.js"></script>
<script>
  const { animate } = anime;
</script>

Local file:

ES6 Modules:

<script type="module">
  import { animate } from './path/to/anime.esm.min.js';
</script>

UMD Modules:

<script type="module">
  import { animate } from './path/to/anime.esm.min.js';
</script>

Global object:

<script src="path/to/anime.iife.min.js"></script>
<script>
  const { animate } = anime;
</script>

Basic usage (v4+):

1. Creating animations with Anime.js starts with the animate() method. This function accepts a target (CSS selector, DOM element, JavaScript object, or array of targets) and an options object that defines the animation:

const animation = animate('.element', {
  translateX: 100,
  scale: 2,
  opacity: .5,
  // start and end values
  x: '6rem',
  y: $el => $el.dataset.y,
  // OR
  x: {
    to: 100,
    delay: 0,
    ease: 'inOut(4)'
  },
  // Keyframes
  x: [0, 100, 200],
  y: [0, 100, 200],
  // OR
  keyframes: [
    { x: 100, y: 100 },
    { x: 200, y: 200 },
  ],         
  // OR
  keyframes: {  
    '0%'  : { x: 0,   y: 0   },
    '50%' : { x: 100, y: 100 },
    '100%': { x: 200, y: 200 }, 
  },             
  duration: 400,
  delay: 250,
  ease: 'out(3)',
  loop: 3,
  alternate: true,
  autoplay: false,
  // Callbacks
  onBegin: () => {},
  onLoop: () => {},
  onUpdate: () => {},
});

2. API methods.

animation.play()
animation.reverse()
animation.pause()
animation.restart()
animation.alternate()
animation.resume()
animation.complete()
animation.cancel()
animation.revert()
animation.seek()
animation.stretch()
animation.refresh()

3. Properties.

  • id: Gets or sets a unique identifier (String or Number) for the animation instance.
  • targets: Gets an array containing the element(s) or object(s) being animated.
  • currentTime: Gets or sets the animation’s overall current time position in milliseconds.
  • iterationCurrentTime: Gets or sets the current time position within the current loop iteration in milliseconds.
  • deltaTime: Gets the time elapsed (in ms) between the last frame and the current frame. Useful within onUpdate.
  • progress: Gets or sets the overall animation progress as a value between 0 (start) and 1 (end).
  • iterationProgress: Gets or sets the progress within the current loop iteration as a value between 0 and 1.
  • currentIteration: Gets or sets the current loop iteration count (starting from 1).
  • duration: Gets the total calculated duration of the animation in milliseconds (including delays, iterations).
  • speed: Gets or sets the playback speed multiplier (e.g., 1 is normal, 2 is double speed, 0.5 is half speed).
  • fps: Gets or sets the target frames per second for the animation calculation.
  • paused: Gets or sets the paused state of the animation (Boolean).
  • began: Gets or sets whether the animation has started playing at least once (Boolean).
  • completed: Gets or sets whether the animation has reached its end state (Boolean).
  • reversed: Gets or sets whether the animation’s direction is currently reversed (Boolean).

Available Modules for Advanced Animations:

Anime.js 4.0 uses a modular architecture that allows you to import only what you need. Check out the Official Documentation for more details.

  • Timer: Think of this as a requestAnimationFrame-synchronized alternative to setTimeout or setInterval. You schedule function callbacks to run at specific times or intervals, perfectly synced with the main Anime.js animation loop (driven by the Engine). This is crucial when you need actions (like adding/removing classes, updating non-animatable properties, or triggering external logic) to happen at precise moments relative to your animations, avoiding timing mismatches you might get with standard browser timers.
  • Timeline: This is the workhorse for choreographing complex animation sequences. Instead of manually chaining animations with delays or onComplete callbacks (which can become brittle), you create a timeline instance and .add() animation definitions or Timer callbacks to it. The timeline manages the overall sequence, allowing you to define precise start times, overlaps, and gaps between different animation parts. It treats the entire sequence as a single controllable unit with its own play, pause, seek, reverse, etc. methods. Essential for anything beyond simple, isolated tweens.
  • Animatable: While animate() is great for defining set-and-forget animations, Animatable is optimized for situations where property values change very frequently based on external factors – think tracking mouse cursor movement, reacting to real-time data, or driving animations within a requestAnimationFrame loop you manage yourself. It’s designed for high-performance, continuous updates by efficiently setting target properties without the overhead of creating a full new animation instance each time. Consider it a more direct, performant way to apply interpolated values when the source of those values is constantly changing.
  • Draggable: This module provides a full-featured system for making DOM elements interactive via dragging. It handles pointer events (mouse/touch), calculates movement, and allows configuration for constraints (axis locking, boundaries), snapping behavior (grid or specific points), inertia/flicking after release, and resistance. It comes with a comprehensive set of callbacks (onDragStart, onDrag, onDragEnd, onThrow, etc.) and methods to programmatically control the draggable state. It’s a self-contained solution for adding drag-and-drop UI features.
  • ScrollObserver: This tackles the common need to trigger or control animations based on scroll position. Instead of manually implementing IntersectionObserver or scroll event listeners and calculating progress, ScrollObserver lets you define trigger elements and link them to Anime.js Animation, Timeline, or Timer instances. You can configure various synchronization modes (e.g., play animation when element enters view, scrub through timeline based on scroll progress within a section) and define precise trigger points (thresholds). It simplifies creating scroll-driven narratives or reveal effects.
  • Scope: Scope is designed for component-based architectures (React, Vue, Svelte, Web Components) and responsive design. You create a scope, often tied to a specific component’s root element. Animations defined within that scope can:
    • React to media query changes (automatically adjusting or reverting animations based on viewport size).
    • Use the scope’s root element for calculations or targeting.
    • Share default animation parameters defined at the scope level.
    • Be managed (e.g., reverted) collectively when the scope/component is unmounted or conditions change. It helps encapsulate animation logic and makes responsive adjustments cleaner.
  • Stagger: A powerful utility function for creating sequential or distributed effects across multiple targets (like elements in a list or grid). Instead of manually calculating delays for each target, stagger() provides helper functions to generate delays or even property values that increment progressively based on index, position, or other factors. It supports different distribution patterns (e.g., linear, from center, from edges, random) and can stagger time delays or the actual animated values themselves. Great for visually appealing entrance/exit animations on collections of items.
  • SVG: This module bundles several utilities specifically for SVG animation, which often involves unique attributes:
    • Shape Morphing: Helps animate the d attribute of <path> elements, allowing smooth transitions between different shapes (requires compatible path data).
    • Line Drawing: Simplifies animating the stroke-dashoffset and stroke-dasharray attributes to create the effect of lines being drawn or erased.
    • Motion Path: Provides helpers to make an element follow the trajectory of an SVG <path>. You define the path, and Anime.js handles animating the element’s transform properties (translateX, translateY, rotate) to follow it.
  • Utilities: A collection of miscellaneous helper functions useful for common animation tasks or for use as modifier functions within animations. This might include functions for things like random number generation within specific ranges, mapping values, clamping, unit conversions, or other small, reusable pieces of logic that often crop up when defining complex or dynamic animations. Check the docs for the specific helpers available.
  • Web Animation API (WAAPI): This module acts as a bridge, allowing you to use the familiar Anime.js API syntax but have it generate animations powered by the browser’s native Web Animations API where supported. The potential benefit is leveraging native browser performance optimizations for animations. It aims to give you the developer experience of Anime.js with the potential performance characteristics of WAAPI, although WAAPI itself has nuances and browser inconsistencies to be aware of.
  • Engine: This is the internal heart of Anime.js, driving the main requestAnimationFrame loop. It manages the timing, updates, and synchronization of all active Animation, Timer, and Timeline instances. You typically don’t interact with the Engine directly, but understanding its role helps grasp how everything stays in sync.

Changelog:

v4.0.2 (04/24/2025)

  • Bugfixes

v4.0.1 (04/09/2025)

  • Bugfix

v4.0.0 (04/06/2025)

  • Major update

v3.2.0 (04/28/2020)

  • Add matrix and matrix3d parameters to allow the use of matrix values in CSS Transforms
  • Change steps easing behaviour to match jump-start CSS timing function
  • Fix (again) a bug where the animation will “flick” on reverse

v3.1.0 (07/27/2019)

  • Add support for values with exponent
  • Easing functions refactoring + added Bounce easing
  • Bug fixes

v3.0.1 (01/17/2019)

  • Direction parameter is now properly changed when animation reverse

01/12/2019

  • Fix change callbacks

06/18/2018

  • v2.2.0

You Might Be Interested In:


Leave a Reply