# dotlottie-js (legacy)
Discover dotlottie-js, a powerful JavaScript library for creating, reading, and manipulating .lottie files in browser and Node.js environments.

# dotlottie-js: Programmatic dotLottie File Creation and Manipulation

<Callout type="warning" title="Superseded by dotlottie-io">
  `dotlottie-io` now supersedes this library. Please prioritize using `dotlottie-io` rather than `dotlottie-js`.
</Callout>

## Introduction

`dotlottie-js` is a comprehensive JavaScript library for programmatically creating, reading, manipulating, and exporting **dotLottie (`.lottie`) files**. Designed for both browser and Node.js environments, it provides developers with the tools to build sophisticated animation workflows, tooling, and content management systems that work with Lottie animations.

### What is dotLottie?

Before understanding `dotlottie-js`, it's essential to understand the **dotLottie (`.lottie`) format**—an open-source, zipped archive format optimized for packaging Lottie animations. Think of it as a specialized ZIP container that bundles:

- **Multiple Lottie animations** (JSON files)
- **Image assets** (PNG, JPEG) used by animations
- **Audio assets** for synchronized sound
- **Metadata** (author, version, generator information)
- **Advanced V2 features** like [Theming](/docs/tools/dotlottie-js/how-to-guides/manage-themes) and [State Machines](/docs/tools/dotlottie-js/how-to-guides/manage-state-machines)

Benefits include smaller file sizes through compression, simplified asset management, and enhanced capabilities beyond standard Lottie JSON files. Learn more at [dotlottie.io](https://dotlottie.io/).

### Role in the Lottie Ecosystem

`dotlottie-js` occupies a specific position in the Lottie ecosystem:

- **dotlottie-js**: Creates and manipulates `.lottie` archives
- **Players**: Render and play `.lottie` files (web, mobile, frameworks)
- **relottie**: Processes and transforms Lottie JSON using AST-based plugins

## Key Capabilities & Features

### Core Operations

- **Create dotLottie Archives**: Bundle multiple animations, images, and resources into a single `.lottie` file
- **Load and Parse Files**: Read `.lottie` files from URLs, ArrayBuffers, or file systems
- **Manipulate Content**: Add, remove, or modify animations, themes, and state machines
- **Manage Assets**: Handle image and audio assets with automatic path resolution
- **Export Multiple Formats**: Output as ArrayBuffer, Blob, Base64, or trigger browser downloads
- **Version Management**: Work with and convert between V1 and V2 dotLottie structures

### Advanced Features (V2)

- **[Theming](/docs/tools/dotlottie-js/how-to-guides/manage-themes)**: Package multiple visual styles (color palettes, property overrides) in a single file
- **[State Machines](/docs/tools/dotlottie-js/how-to-guides/manage-state-machines)**: Define interactive behaviors and animation control logic
- **Multi-Animation Support**: Organize related animations with manifest-based selection
- **Metadata Management**: Embed author, version, description, and custom metadata

### Platform Support

| Environment        | Support   | Notes                                               |
| ------------------ | --------- | --------------------------------------------------- |
| **Browser**        | ✅ Full    | All features including `download()` method          |
| **Node.js**        | ✅ Full    | Use `toArrayBuffer()` with `fs` module for file I/O |
| **Edge Functions** | ✅ Partial | Check runtime limitations for file I/O              |
| **Webpack/Vite**   | ✅ Full    | Standard module bundler support                     |

## Architecture & How It Works

### Internal Structure

```
┌─────────────────────────────────────────────────────────┐
│              dotlottie-js Architecture                  │
├─────────────────────────────────────────────────────────┤
│                                                         │
│  ┌──────────────┐                                       │
│  │  DotLottie   │  Main API Class                       │
│  │   Instance   │                                       │
│  └──────┬───────┘                                       │
│         │                                               │
│         ├─▶ Animation Manager   (add/remove/get)        │
│         ├─▶ Theme Manager        (V2 features)          │
│         ├─▶ State Machine Mgr    (V2 features)          │
│         ├─▶ Asset Manager        (images/audio)         │
│         ├─▶ Manifest Builder     (metadata)             │
│         └─▶ ZIP Archiver         (compression)          │
│                                                         │
│  Build Process:                                         │
│  1. Validate configuration                              │
│  2. Fetch remote resources (if URLs provided)           │
│  3. Process and embed assets                            │
│  4. Generate manifest.json                              │
│  5. Create ZIP archive structure                        │
│  6. Compress and output                                 │
│                                                         │
└─────────────────────────────────────────────────────────┘
```

### Build Workflow

1. **Instantiate**: Create a `DotLottie` instance
2. **Configure**: Add animations, themes, state machines, and assets
3. **Build**: Call `build()` to fetch resources and compile the archive
4. **Export**: Use `download()`, `toArrayBuffer()`, `toBlob()`, or `toBase64()`

## Quick Start

### Installation

Install using your preferred package manager:

```bash
# npm
npm install @dotlottie/dotlottie-js

# pnpm
pnpm add @dotlottie/dotlottie-js

# yarn
yarn add @dotlottie/dotlottie-js
```

### Basic Usage: Create and Download

```javascript
import { DotLottie } from "@dotlottie/dotlottie-js";

async function createAnimation() {
  // 1. Create instance
  const dotlottie = new DotLottie();

  // 2. Add animation from URL
  dotlottie.addAnimation({
    id: "animation_1",
    url: "https://assets.lottiefiles.com/packages/lf20_jW54t3.json",
    name: "My Animation",
  });

  // 3. Build the archive
  await dotlottie.build();

  // 4. Download (browser) or export
  await dotlottie.download("my-animation.lottie");
}
```

### Node.js: Export to File System

```javascript
import { DotLottie } from "@dotlottie/dotlottie-js";
import { writeFile } from "fs/promises";

async function createAnimationNode() {
  const dotlottie = new DotLottie();

  // Add animation from local JSON object
  const animationData = {
    v: "5.9.6",
    fr: 60,
    ip: 0,
    op: 180,
    w: 512,
    h: 512,
    layers: [],
  };

  dotlottie.addAnimation({
    id: "animation_1",
    data: animationData,
  });

  await dotlottie.build();

  // Export as ArrayBuffer and save
  const arrayBuffer = await dotlottie.toArrayBuffer();
  await writeFile("output.lottie", Buffer.from(arrayBuffer));
}
```

## Common Use Cases

### 1. Animation Authoring Tools

Build tools that allow designers to configure and export `.lottie` files:

```javascript
const dotlottie = new DotLottie();

// Add multiple animations
dotlottie.addAnimation({
  id: "idle",
  data: idleAnimation,
});

dotlottie.addAnimation({
  id: "hover",
  data: hoverAnimation,
});

// Add theme for dark mode — theme data is { rules: [...] }, where each
// rule's `id` matches a themeable property tagged in the animation
dotlottie.addTheme({
  id: "dark",
  data: {
    rules: [
      { id: "primary_color", type: "Color", value: [1, 1, 1, 1] },
      { id: "accent_color", type: "Color", value: [0, 0.66, 1, 1] },
    ],
  },
});

await dotlottie.build();
await dotlottie.download("button-animation.lottie");
```

### 2. Server-Side Dynamic Generation

Generate customized animations on-demand:

```javascript
import { DotLottie } from "@dotlottie/dotlottie-js";

// brandColors example: { primary_color: [0.1, 0.2, 0.8, 1], accent_color: [1, 0.5, 0, 1] }
// — keys are themeable property IDs, values are RGBA arrays in the 0-1 range
async function generateUserAnimation(userId, brandColors) {
  const dotlottie = new DotLottie();

  // Fetch base animation
  dotlottie.addAnimation({
    id: "base",
    url: "https://cdn.example.com/base-animation.json",
  });

  // Add user-specific theme — theme data is { rules: [...] }
  dotlottie.addTheme({
    id: "user_theme",
    data: {
      rules: Object.entries(brandColors).map(([id, value]) => ({ id, type: "Color", value })),
    },
  });

  await dotlottie.build();
  return await dotlottie.toArrayBuffer();
}
```

### 3. Build Pipeline Automation

Automate animation bundling in CI/CD:

```javascript
import { DotLottie } from "@dotlottie/dotlottie-js";
import { readFile, writeFile } from "fs/promises";
import { glob } from "glob";

async function bundleAnimations() {
  const dotlottie = new DotLottie();
  const animationFiles = await glob("src/animations/*.json");

  for (const file of animationFiles) {
    const data = JSON.parse(await readFile(file, "utf-8"));
    const id = file.match(/([^/]+)\.json$/)[1];

    dotlottie.addAnimation({
      id,
      data,
    });
  }

  await dotlottie.build();
  const buffer = await dotlottie.toArrayBuffer();
  await writeFile("dist/animations.lottie", Buffer.from(buffer));
}
```

### 4. Interactive Animation Builder

Create animations with state machine interactivity:

```javascript
const dotlottie = new DotLottie();

dotlottie.addAnimation({
  id: "button_animation",
  data: buttonAnimationData,
});

// Add state machine for interaction — data is { initial, states, inputs?, interactions? }
dotlottie.addStateMachine({
  id: "button_states",
  data: {
    initial: "idle",
    states: [
      {
        name: "idle",
        type: "PlaybackState",
        animation: "button_animation",
        segment: "0 30",
        autoplay: true,
        transitions: [{ type: "Transition", toState: "hover", guards: [{ type: "Event", inputName: "onHover" }] }],
      },
      {
        name: "hover",
        type: "PlaybackState",
        animation: "button_animation",
        segment: "30 60",
        autoplay: true,
        transitions: [
          { type: "Transition", toState: "idle", guards: [{ type: "Event", inputName: "onLeave" }] },
          { type: "Transition", toState: "clicked", guards: [{ type: "Event", inputName: "onClick" }] },
        ],
      },
      {
        name: "clicked",
        type: "PlaybackState",
        animation: "button_animation",
        segment: "60 90",
        autoplay: true,
        transitions: [
          { type: "Transition", toState: "idle", guards: [{ type: "Event", inputName: "onAnimComplete" }] },
        ],
      },
    ],
    inputs: [
      { type: "Event", name: "onHover" },
      { type: "Event", name: "onLeave" },
      { type: "Event", name: "onClick" },
      { type: "Event", name: "onAnimComplete" },
    ],
    interactions: [
      { type: "PointerEnter", actions: [{ type: "Fire", inputName: "onHover" }] },
      { type: "PointerExit", actions: [{ type: "Fire", inputName: "onLeave" }] },
      { type: "PointerDown", actions: [{ type: "Fire", inputName: "onClick" }] },
      { type: "OnComplete", stateName: "clicked", actions: [{ type: "Fire", inputName: "onAnimComplete" }] },
    ],
  },
});

await dotlottie.build();
```

## Tool Comparison

### When to Use dotlottie-js

✅ **Use dotlottie-js when you need to:**

- Create `.lottie` files programmatically
- Bundle multiple animations into a single file
- Add themes or state machines to animations
- Build animation authoring tools
- Generate customized animations server-side
- Automate animation packaging in build pipelines
- Manage assets alongside animations

❌ **Don't use dotlottie-js when you:**

- Only need to play animations (use Players instead)
- Need to transform/optimize Lottie JSON structure (use relottie)
- Want to analyze animation features (use relottie)

### dotlottie-js vs. relottie

| Aspect               | dotlottie-js               | relottie                   |
| -------------------- | -------------------------- | -------------------------- |
| **Focus**            | `.lottie` container format | Lottie JSON transformation |
| **Approach**         | File packaging             | AST processing             |
| **Strength**         | Multi-animation bundles    | Deep JSON manipulation     |
| **Plugin system**    | No                         | Yes (unified.js)           |
| **Asset management** | Full support               | Not applicable             |
| **Use case**         | Create archives            | Transform animations       |

**Example workflow**: Use `relottie` to optimize/transform individual Lottie JSON files, then use `dotlottie-js` to bundle them with themes into a `.lottie` archive.

### Combined Workflow

For enterprise applications, you might use all three:

```javascript
// 1. Transform animations with relottie
import { relottie } from "@lottiefiles/relottie";
import relottieParse from "@lottiefiles/relottie-parse";
import relottieStringify from "@lottiefiles/relottie-stringify";
import optimizePlugin from "@lottiefiles/some-optimize-plugin";

const optimized = await relottie()
  .use(relottieParse)
  .use(optimizePlugin)
  .use(relottieStringify)
  .process(lottieJsonString);

// 2. Package with dotlottie-js
import { DotLottie } from "@dotlottie/dotlottie-js";

const dotlottie = new DotLottie();
dotlottie.addAnimation({
  id: "optimized",
  data: JSON.parse(optimized.value),
});

await dotlottie.build();
const dotlottieFile = await dotlottie.toArrayBuffer();

// 3. Play with a Player (in browser)
// <dotlottie-player src="path/to/file.lottie"></dotlottie-player>
```

## API Overview

The library centers around the `DotLottie` class:

```javascript
import { DotLottie } from "@dotlottie/dotlottie-js";

const dotlottie = new DotLottie();

// Optional constructor options — only `generator` and
// `enableDuplicateImageOptimization` are supported:
const dotlottieWithOptions = new DotLottie({
  generator: "MyApp/1.0", // written to manifest.json
  enableDuplicateImageOptimization: true, // de-dupe identical images on build()
});
```

### Core Methods

| Method                     | Purpose                | Environment  |
| -------------------------- | ---------------------- | ------------ |
| `addAnimation(options)`    | Add Lottie animation   | Both         |
| `addTheme(options)`        | Add visual theme (V2)  | Both         |
| `addStateMachine(options)` | Add interactivity (V2) | Both         |
| `build()`                  | Compile archive        | Both         |
| `download(filename)`       | Trigger download       | Browser only |
| `toArrayBuffer()`          | Get raw binary         | Both         |
| `toBlob()`                 | Get Blob               | Browser only |
| `toBase64()`               | Get Base64 string      | Both         |
| `fromArrayBuffer(buffer)`  | Load existing file     | Both         |

### Code Example: Complete Workflow

```javascript
import { DotLottie } from "@dotlottie/dotlottie-js";

async function completeExample() {
  // Create the instance
  const dotlottie = new DotLottie({
    generator: "Design Team Animation Builder", // optional: written to manifest.json
  });

  // Add animations
  dotlottie.addAnimation({
    id: "loading",
    url: "https://example.com/loading.json",
    name: "Loading Spinner",
  });

  dotlottie.addAnimation({
    id: "success",
    data: successAnimationData,
    name: "Success Checkmark",
  });

  // Add light and dark themes — theme data is { rules: [...] }
  dotlottie.addTheme({
    id: "light",
    data: { rules: [{ id: "primary_color", type: "Color", value: [0, 0, 0, 1] }] },
  });

  dotlottie.addTheme({
    id: "dark",
    data: { rules: [{ id: "primary_color", type: "Color", value: [1, 1, 1, 1] }] },
  });

  // Images aren't added via a standalone method — bundle them by including
  // an "assets" array in the Lottie JSON you pass to addAnimation(). See
  // /docs/tools/dotlottie-js/how-to-guides/manage-assets.

  // Build and export
  await dotlottie.build();

  // Choose export method based on environment
  if (typeof window !== "undefined") {
    // Browser: download
    await dotlottie.download("animations.lottie");
  } else {
    // Node.js: save to file
    const buffer = await dotlottie.toArrayBuffer();
    await writeFile("animations.lottie", Buffer.from(buffer));
  }
}
```

## Performance Considerations

### Best Practices

1. **Reuse instances**: Create one `DotLottie` instance per archive
2. **Build once**: Call `build()` only after all content is added
3. **Optimize animations**: Use relottie to optimize JSON before bundling
4. **Lazy load**: For large archives, load animations on-demand from URLs
5. **Compression**: The format automatically compresses; no additional steps needed

### Memory Management

- **Large files**: Use streams when available (Node.js)
- **Multiple archives**: Clear references after export
- **Asset handling**: Images are automatically embedded and compressed

## Next Steps

### Tutorials

- **[Build Your First `.lottie` File](/docs/tools/dotlottie-js/tutorials/first-lottie-file)**: A hands-on, start-to-finish walkthrough

### How-To Guides

- **[Install dotlottie-js](/docs/tools/dotlottie-js/how-to-guides/install)**: Set up the library in your project
- **[Create and Export a `.lottie` File](/docs/tools/dotlottie-js/how-to-guides/create-and-export-a-lottie-file)**: Package an animation and export it
- **[Load a `.lottie` File](/docs/tools/dotlottie-js/how-to-guides/load-a-lottie-file)**: Read and inspect an existing file
- **[Manage Animations](/docs/tools/dotlottie-js/how-to-guides/manage-animations)**: Add, remove, and configure animations
- **[Manage Assets](/docs/tools/dotlottie-js/how-to-guides/manage-assets)**: Work with images and audio
- **[Manage Themes](/docs/tools/dotlottie-js/how-to-guides/manage-themes)**: Package multiple visual styles
- **[Manage State Machines](/docs/tools/dotlottie-js/how-to-guides/manage-state-machines)**: Add interactivity
- **[Merge Instances](/docs/tools/dotlottie-js/how-to-guides/merge-instances)**: Combine multiple `.lottie` files
- **[Export a `.lottie` File](/docs/tools/dotlottie-js/how-to-guides/export-a-lottie-file)**: Output in various formats
- **[Migrate from pre-1.0](/docs/tools/dotlottie-js/how-to-guides/migrate-from-pre-1.0)**: Upgrade from older versions

### Reference

- **[API Reference](/docs/tools/dotlottie-js/reference)**: Complete class and utility documentation
- **[Platform Support](/docs/tools/dotlottie-js/reference/platform-support)**: Browser and Node.js specifics
- **[Format Versions](/docs/tools/dotlottie-js/reference/format-versions)**: V1 vs V2 comparison and the manifest.json schema

### Ecosystem

- **[Contributing](/docs/tools/dotlottie-js/ecosystem/contributing)**: Project setup and how to contribute
- **[dotlottie.io](https://dotlottie.io/)**: Official format specification
- **[dotLottie Players](/en/runtimes/)**: Render .lottie files
- **[relottie](/docs/tools/relottie)**: Transform Lottie JSON
