Lottie-web

repository·master·Indexed 13 days ago

https://github.com/airbnb/lottie-web

A JavaScript library that parses Adobe After Effects animations exported as JSON via Bodymovin and renders them natively in web browsers using SVG, Canvas, or HTML. Version 5.13.0 includes methods for animation control, global playback management, and HTML attribute-based registration.

Tokens
2.2K
Snippets
6
Records
11
Agent score
49%

What's inside Lottie

  1. Supported After Effects features

    master

    The Lottie export process supports several After Effects features, but also has specific limitations:

    Supported:

    • Precomps, shapes, solids, images, null objects, and texts.
    • Shapes: rectangles, ellipses, and stars.
    • Masks and inverted masks.
    • Time remapping.
    • Expressions (refer to the Bodymovin wiki for details).

    Not Supported:

    • Image sequences.
    • Videos.
    • Audio.
    • Negative layer stretching: Stretching a layer negatively will corrupt the data.
  2. Optimize Lottie animation performance

    master

    Lottie performs real-time rendering. To ensure optimal performance, follow these recommendations:

    • Simplify AE Projects: Keep After Effects projects as minimal as possible.
    • Avoid Large Masks: Do not use extremely large shapes in After Effects just to mask a small portion of them.
    • Minimize Nodes: Reducing the number of nodes in your animation will improve performance.
    • Convert AI Layers: For images or Adobe Illustrator layers, it is recommended to convert them to shapes (Right-click layer -> "Create shapes from Vector Layers") so they are exported as vectors.
    • Compression: Gzipping both the animation JSON files and the player results in a significant reduction in file size. It is highly recommended for production projects.
  3. Configure rendererSettings

    master

    When using loadAnimation, you can pass a rendererSettings object to fine-tune the renderer behavior. This is particularly useful when using the canvas renderer.

    Common rendererSettings keys:

    • context: The canvas context (e.g., '2d'). Required if providing an existing canvas.
    • preserveAspectRatio: Supports same options as the SVG preserveAspectRatio property (e.g., 'xMinYMin slice').
    • title: Adds an SVG <title> element for accessibility.
    • description: Adds an SVG <desc> element for accessibility.
    • clearCanvas: Boolean.
    • progressiveLoad: (SVG only) If true, loads DOM elements when needed to speed up initialization.
    • hideOnTransparent: (SVG only) If true, hides elements when opacity reaches 0.
    • className: CSS class to add to the renderer.
    • id: Unique ID for the renderer.
    lottie.loadAnimation({
      container: element,
      renderer: 'svg',
      loop: true,
      autoplay: true,
      animationData: animationData,
      rendererSettings: {
        context: canvasContext,
        preserveAspectRatio: 'xMinYMin slice',
        title: 'Accessible Title',
        description: 'Accessible description.',
        clearCanvas: false,
        progressiveLoad: false,
        hideOnTransparent: true,
        className: 'some-css-class-name',
        id: 'some-id',
      }
    });
  4. Fix missing masks in Safari

    master

    If you encounter issues where masks are missing when using the Safari browser, this is often caused by the use of a <base> tag in your HTML. To resolve this, call lottie.setLocationHref(locationHref) before the animation is generated.

    lottie.setLocationHref(locationHref);
  5. Register animations via HTML attributes

    master

    Instead of calling loadAnimation in JavaScript, you can declare animations directly in your HTML. Lottie will automatically find and load them if you call lottie.searchAnimations() or if they are present at page load.

    Requirements:

    • The element must have the class lottie.
    • The element must have a data-animation-path attribute pointing to the .json file.

    Optional Attributes:

    • data-anim-loop: Set to true or false.
    • data-name: A unique name to target this animation specifically via global methods.

    Example:

    <div class="lottie" data-animation-path="animation/data.json" data-anim-loop="true" data-name="ninja"></div>
     <div style="width:1067px;height:600px"  class="lottie" data-animation-path="animation/" data-anim-loop="true" data-name="ninja"></div
  6. Load an animation with loadAnimation()

    master

    The lottie.loadAnimation() method is the primary way to start an animation. It accepts a configuration object and returns an animation instance that you can control.

    Important Note on animationData: If your animation contains repeaters and you plan to call loadAnimation multiple times with the same animation data, you must deep clone the object before passing it to avoid state issues.

    Configuration Options:

    • container: The DOM element on which to render the animation.
    • renderer: 'svg', 'canvas', or 'html'.
    • loop: true, false, or a number.
    • autoplay: true or false (starts playing as soon as ready).
    • name: A string name for the animation for future reference.
    • path: The relative path to the animation JSON file. (Note: animationData and path are mutually exclusive).
    • animationData: An object containing the exported animation data.
    • rendererSettings: An object for renderer-specific configurations (see Renderer Settings).
    lottie.loadAnimation({
      container: element, // the dom element that will contain the animation
      renderer: 'svg',
      loop: true,
      autoplay: true,
      path: 'data.json' // the path to the animation json
    });
  7. Use global lottie methods to control all animations

    master

    Lottie provides global methods that can target all animations or a specific animation by its name:

    • lottie.play([name])
    • lottie.stop([name])
    • lottie.pause([name])
    • lottie.setSpeed(speed, [name])
    • lottie.setDirection(direction, [name])
    • lottie.goToAndStop(value, isFrame, [name])
    • lottie.destroy(name): Destroys animation(s). If name is omitted, all instances are destroyed.
    • lottie.searchAnimations(): Looks for elements with class lottie or bodymovin and registers them.
    • lottie.getRegisteredAnimations(): Returns all animation instances.
    • lottie.setQuality(quality): Sets quality to 'high', 'medium', 'low', or a number > 1.
    • lottie.resize(): Resizes all animation instances.
  8. Control an animation instance

    master

    The object returned by lottie.loadAnimation() provides methods to control the playback of a specific animation instance:

    • play(): Starts playback.
    • pause(): Pauses playback.
    • stop(): Stops playback.
    • setSpeed(speed): Sets playback speed (1 is normal speed).
    • setDirection(direction): Sets playback direction (1 for forward, -1 for reverse).
    • goToAndStop(value, isFrame): Moves to a specific time or frame. isFrame (boolean, default false) determines if value is a frame or time-based value.
    • goToAndPlay(value, isFrame): Moves to a specific time or frame and plays.
    • playSegments(segments, forceFlag): Plays a specific segment. segments is an array of numeric pairs (e.g., [[0, 10], [20, 30]]). forceFlag (boolean) if true updates immediately; if false, it waits for the current segment to finish.
    • getDuration(inFrames): Returns duration. If inFrames is true, returns frames; otherwise, returns seconds.
    • destroy(): Destroys the animation instance and clears the DOM element.
    • setSubframe(useSubFrames): If true (default), updates on every requestAnimationFrame with intermediate values for smoother motion. If false, respects original AE FPS.
  9. Listen to Lottie animation events

    master

    You can listen to animation lifecycle events using addEventListener or by assigning them to the animation instance.

    Available Events:

    • complete: Triggered when the animation finishes.
    • loopComplete: Triggered when a loop completes.
    • drawnFrame: Triggered on every frame drawn.
    • enterFrame: Triggered on every frame.
    • segmentStart: Triggered when a segment starts.
    • config_ready: Triggered when initial configuration is done.
    • data_ready: Triggered when all parts of the animation have been loaded.
    • data_failed: Triggered when part of the animation cannot be loaded.
    • loaded_images: Triggered when image loads succeed or error.
    • DOMLoaded: Triggered when elements are added to the DOM.
    • destroy: Triggered when the animation is destroyed.