DotLottie Class
API documentation for the DotLottie (V2) class in dotlottie-js. Learn to create, manage, and export V2 dotLottie files.
DotLottie Class API
The DotLottie class is the primary interface for working with dotLottie (V2) files. It allows creating new .lottie archives, loading existing V1 or V2 files, managing animations, assets (images, audio), themes, and state machines, and exporting the result.
Import:
import { DotLottie } from "@dotlottie/dotlottie-js";Constructor
Creates a new, empty DotLottie instance, ready to be populated.
new DotLottie(options?: DotLottieOptions)
Parameters:
options(optional):DotLottieOptions- An object to configure the instance.generator?: string: Sets the generator tool metadata. (Default: Name and version of thedotlottie-jslibrary)enableDuplicateImageOptimization?: boolean: Iftrue, the library will attempt to de-duplicate identical images added to the archive to save space. When an image is added that is identical to an existing one, the new animation will reference the existing image ID instead of adding a new copy. (Default:false)
Returns:
DotLottie: A newDotLottieinstance.
Example:
// Create with default options
const dotlottie = new DotLottie();
// Create with custom options
const customDotLottie = new DotLottie({
generator: "LottieFiles",
enableDuplicateImageOptimization: true,
});Loading Existing Files (Instance Methods)
Use these asynchronous methods on a DotLottie instance to load data from an existing .lottie file (V1 or V2) into it.
async fromArrayBuffer(arrayBuffer: ArrayBuffer): Promise<DotLottie>
Asynchronously loads a dotLottie animation from an ArrayBuffer into a new instance. If the buffer contains a V1 dotLottie file, it will be automatically converted to the V2 structure within this instance.
Parameters:
arrayBuffer:ArrayBuffer- The ArrayBuffer containing the.lottiefile data.
Returns:
Promise<DotLottie>: A promise that resolves to a new DotLottie instance, populated with data from the buffer.
Example:
async function loadFromArrayBuffer(buffer) {
try {
const dotlottie = await new DotLottie().fromArrayBuffer(buffer); // Load into a new DotLottie instance
console.log("Loaded from ArrayBuffer:", dotlottie.animations.length, "animation(s)");
return dotlottie;
} catch (error) {
console.error("Failed to load from ArrayBuffer:", error);
}
}async fromURL(url: string): Promise<DotLottie>
Asynchronously fetches and loads a dotLottie animation from a URL into a new instance. If the URL points to a V1 dotLottie file, it will be automatically converted to the V2 structure within this instance.
Parameters:
url:string- The URL of the.lottiefile.
Returns:
Promise<DotLottie>: A promise that resolves to a new DotLottie instance, populated with data from the URL.
**Example (Browser/Node.js with fetch capabilities): **
async function loadFromURL(fileUrl): DotLottie | undefined {
try {
const dotlottie = await new DotLottie().fromURL(fileUrl); // create new instance
console.log("Loaded from URL:", dotlottie.animations.length, "animation(s)");
return dotlottie;
} catch (error) {
console.error("Failed to load from URL:", error);
}
}
// Example usage:
// const myDotLottie = await loadFromURL('https://example.com/animation.lottie');Instance Properties and Methods
Once a DotLottie instance is available (created new or loaded), use its properties and methods to manage content and export it.
Managing Animations
These methods and properties add, remove, and access animations within the dotLottie archive. Each animation typically corresponds to a Lottie JSON file.
addAnimation(animationOptions: AnimationOptions): this
Adds a new Lottie animation to the archive.
Parameters:
animationOptions:AnimationOptions- An object describing the animation to add.id:string- A unique identifier for this animation within the archive.data:Record<string, any>- The Lottie JSON animation data as a JavaScript object. Important: Any assets (images, audio) defined within thisdata(in theassetsarray) will be processed during thebuild()step. If assets are embedded (Base64 inp), their data will be extracted and bundled. If assets reference external files (pcontains a filename), ensure those assets are available or handled appropriately (e.g., fetched ifdatawas a URL). See Managing Assets.url?: string: (Optional) A URL pointing to the Lottie JSON file. If provided,dotlottie-jswill fetch this URL during theawait dotlottie.build()step. You must provide eitherdataorurl.loop?: boolean: (Optional) Whether the animation should loop. (Default:false)speed?: number: (Optional) The playback speed. (Default:1)themeColor?: string: (Optional) A default theme color for this animation. (Default:undefined)autoplay?: boolean: (Optional) Whether the animation should autoplay. (Default:false)hover?: boolean: (Optional) Set to true if this animation is meant to play on hover. (Default:false)intermission?: number: (Optional) Time in milliseconds between animation loops. (Default:0)initialTheme?: string: (Optional) The ID of the theme to apply by default when this animation loads. Requires a theme with the matching ID to be added viaaddTheme().
Returns:
this(theDotLottieinstance for chaining).Example:
const lottieJsonData = { v: "5.5.7", fr: 30, ip: 0, op: 150, w: 1920, h: 1080, nm: "My Animation", assets: [ { id: "image_0", w: 100, h: 50, u: "", p: "data:image/png;base64,iVBORw0...", }, // Embedded { id: "image_1", w: 200, h: 150, u: "images/", p: "external_image.jpg" }, // External reference ], layers: [ /* ... */ ], }; dotlottie.addAnimation({ id: "anim1", data: lottieJsonData, loop: true, speed: 0.5, });
removeAnimation(animationId: string): this
Removes an animation from the archive by its ID. Does nothing if an animation with the given ID is not found.
Parameters:
animationId:string- The ID of the animation to remove.
Returns:
this(theDotLottieinstance for chaining).Example:
dotlottie.removeAnimation('anim1');
getAnimation(animationId: string): object | undefined
Retrieves an object representing a specific animation by its ID. This object holds the animation's manifest properties and allows access to its underlying Lottie JSON data.
Parameters:
animationId:string- The ID of the animation to retrieve.
Returns:
object | undefined- An object representing the animation if found, orundefined. The object has properties such as:id: stringname?: stringloop?: booleanspeed?: numberthemeColor?: stringautoplay?: booleanhover?: booleanintermission?: numberinitialTheme?: stringasync toJSON(options?: { inlineAssets?: boolean }): Promise<Record<string, any>>: An asynchronous method to retrieve the raw Lottie JSON data for the animation. Optionally inline assets by passing{ inlineAssets: true }.
Example:
async function exampleGetAnimation() { const animation = dotlottie.getAnimation("my_animation"); if (animation) { console.log("Animation found:", animation.id, "Loop:", animation.loop); try { const animData = await animation.toJSON(); console.log("Lottie JSON:", animData.v); // Access JSON properties } catch (error) { console.error("Error getting animation JSON:", error); } } }
animations: object[] (Getter)
Retrieves an array of objects representing the manifest entries for all animations currently in the archive. Each object has properties like id, name, loop, etc. To get the full Lottie JSON data for a specific entry, use getAnimation(id) and then animation.toJSON().
Returns:
object[]- An array of animation manifest entry objects.
Managing Assets (Images and Audio)
Assets like images and audio are typically managed implicitly through the animations that use them.
Define Assets in Lottie JSON: Ensure your Lottie JSON data (provided to
addAnimation) correctly defines required assets in itsassetsarray.Assets can be embedded directly using Base64 data URLs in the
pproperty (e.g.,"p": "data:image/png;base64,...").Assets can reference external files (e.g.,
"u": "images/", "p": "my_image.png"). If you load a.lottiethat uses external references, the assets should already be bundled within it.
Add Animation: Add the animation(s) using
addAnimation().Build Process: When you call
await dotlottie.build(), the library automatically:Scans the
assetsarrays of all added animations.Extracts data for embedded assets.
Bundles the assets into the archive (e.g.,
images/,audio/.Updates the Lottie JSON within the archive to correctly reference the bundled asset paths.
Optionally de-duplicates images if
enableDuplicateImageOptimizationis true.
You generally do not need to call explicit addImage or addAudio methods.
Accessing Discovered Assets
After loading or building a DotLottie instance, you can inspect the assets that were discovered and bundled.
getImages(): object[]
Retrieves an array of objects representing all unique image assets discovered in the archive. Each object allows access to the image's metadata and data.
Returns:
object[]- An array of image asset objects. Each object has properties such as:id: stringfileName: stringwidth?: numberheight?: numberasync toArrayBuffer(): Promise<ArrayBuffer>: Get image data as ArrayBuffer.async toBase64(): Promise<string>: Get image data as Base64 string.async toBlob(): Promise<Blob>: (Browser only) Get image data as Blob.
getAudio(): object[]
Retrieves an array of objects representing all unique audio assets discovered in the archive. Each object allows access to the audio's metadata and data.
Returns:
object[]- An array of audio asset objects. Each object has properties such as:id: stringfileName: stringasync toArrayBuffer(): Promise<ArrayBuffer>: Get audio data as ArrayBuffer.async toBase64(): Promise<string>: Get audio data as Base64 string.async toBlob(): Promise<Blob>: (Browser only) Get audio data as Blob.
Example:
// After loading or building 'dotlottie'
const allImages = dotlottie.getImages();
console.log(`Found ${allImages.length} unique images.`);
if (allImages.length > 0) {
const firstImage = allImages[0];
console.log(`First image ID: ${firstImage.id}, FileName: ${firstImage.fileName}`);
// const firstImageBuffer = await firstImage.toArrayBuffer();
}
const allAudio = dotlottie.getAudio();
console.log(`Found ${allAudio.length} unique audio assets.`);Managing Themes
Theming allows you to define multiple visual variations for your Lottie animations within a single .lottie file. Themes are stored as separate JSON data structures that players can apply to animations at runtime.
addTheme(theme: Theme): this
Adds a new theme to the archive.
Parameters:
theme:Theme- An object describing the theme.id:string- A unique identifier for this theme.data:Record<string, any>- The theme data, typically an object where keys are layer names (or selectors) and values are objects of properties to override (e.g.,{ "LayerName.Color": "#FF0000" }). The exact structure depends on how your Lottie player and animations are designed to interpret theme data.name?:string- An optional human-readable name for the theme.
Returns:
this(theDotLottieinstance for chaining).Example:
dotlottie.addTheme({ id: "dark-mode", name: "Dark Mode", data: { "background.fill.color": "#000000", "text.fill.color": "#FFFFFF", // Specific layer overrides based on Lottie JSON structure "LayerName1.Color": [1, 0, 0, 1], // Example: Red color for a shape }, });
removeTheme(themeId: string): this
Removes a theme from the archive by its ID. Does nothing if a theme with the given ID is not found.
Parameters:
themeId:string- The ID of the theme to remove.
Returns:
this(theDotLottieinstance for chaining).
getTheme(themeId: string): object | undefined
Retrieves an object representing a specific theme by its ID.
Parameters:
themeId:string- The ID of the theme to retrieve.
Returns:
object | undefined- An object containing the theme'sid,data, and optionalname, orundefinedif not found.
themes: object[] (Getter)
Retrieves an array of objects representing all themes currently in the archive. Each object contains the theme's id, data, and optional name.
Returns:
object[]- An array of theme objects.
Setting an Initial Theme for an Animation
When adding an animation using addAnimation, you can specify an initialTheme property with the theme's ID. Alternatively, you can update it later on a retrieved animation object.
// Option 1: Set during addAnimation
dotlottie.addAnimation({
id: "main-animation",
// data: animationData, // Assuming animationData is defined
initialTheme: "dark-mode", // This theme will be applied by default
});
// Option 2: Update later (needs async context)
async function updateInitialTheme() {
const animation = await dotlottie.getAnimation("main-animation");
if (animation) {
animation.initialTheme = "light-mode"; // Update the default theme
}
}
// updateInitialTheme();
// Remember to call build() again if you modify the instance after an initial build.Managing State Machines
State machines enable interactive Lottie animations. They define states, transitions, and actions that a Lottie player can use to control animation playback based on user input or other events.
For detailed information on the structure and capabilities of Lottie state machines, refer to the official documentation on dotlottie.io.
addStateMachine(stateMachineOptions: StateMachineOptions): this
Adds a new state machine to the archive.
Parameters:
stateMachineOptions:StateMachineOptions- An object describing the state machine.id:string- A unique identifier for this state machine.data:Record<string, any>- The state machine JSON data. This object must conform to the Lottie state machine schema.name?:string- An optional human-readable name.
Returns:
this(theDotLottieinstance for chaining).Example:
const myStateMachineData = { // ... valid Lottie state machine JSON ... descriptor: { id: "button_interaction", // This ID inside the data is crucial initial: "state_A", }, states: { state_A: { /* ... */ }, state_B: { /* ... */ }, }, // ... etc. }; dotlottie.addStateMachine({ id: "sm_button", // ID used in the manifest & for getStateMachine name: "Button Interaction Logic", data: myStateMachineData, });
removeStateMachine(stateMachineId: string): this
Removes a state machine from the archive by its ID. Does nothing if a state machine with the given ID is not found.
Parameters:
stateMachineId:string- The ID of the state machine to remove.
Returns:
this(theDotLottieinstance for chaining).
getStateMachine(stateMachineId: string): object | undefined
Retrieves an object representing a specific state machine by its ID.
Parameters:
stateMachineId:string- The ID of the state machine to retrieve.
Returns:
object | undefined- An object containing the state machine'sid,data, and optionalname, orundefinedif not found.
stateMachines: object[] (Getter)
Retrieves an array of objects representing all state machines currently in the archive. Each object contains the state machine's id, data, and optional name.
Returns:
object[]- An array of state machine objects.
Merging Instances
merge(...dotlotties: DotLottie[]): DotLottie
Creates and returns a new DotLottie instance containing the merged content of the instance it is called on, plus all instances passed as arguments. The original instances are not modified.
Parameters:
...dotlotties:DotLottie[]- One or moreDotLottieinstances to merge with the current instance's content.
Returns:
DotLottie- A newDotLottieinstance containing the combined animations, themes, state machines, etc.Throws: If any duplicate IDs (for animations, themes, or state machines) are found across the combined set of instances (the calling instance + all arguments).
Note: The merge operation itself is synchronous, but the returned instance must be built (
await mergedInstance.build()) before exporting.Example:
const dl1 = new DotLottie(); // Assume dl1 has content const dl2 = new DotLottie(); // Assume dl2 has different content with unique IDs const dl3 = new DotLottie(); // Assume dl3 has different content with unique IDs try { const merged = dl1.merge(dl2, dl3); // Now 'merged' contains content from dl1, dl2, and dl3 // dl1, dl2, dl3 remain unchanged. await merged.build(); // Build the new instance // ... export merged instance ... } catch (error) { console.error("Merge failed (likely duplicate ID):", error); }
Building and Exporting
After you have configured your DotLottie instance by adding animations, assets (implicitly via animations), themes, and state machines, you need to compile these components into the final .lottie archive format before you can export it.
build(): Promise<this>
Asynchronously prepares and finalizes the dotLottie archive. This method must be called after making all modifications (adding/removing animations, themes, state machines, setting metadata) and before calling any of the export methods (toArrayBuffer, toBlob, toBase64, download).
The build() process typically involves:
Validating the manifest data.
Processing and bundling all Lottie animation JSON data.
Processing and bundling all image and audio assets discovered within the animations.
Storing themes and state machine data.
Assembling these into the compressed
.lottie(ZIP) archive structure in memory.Returns:
Promise<this>- A promise that resolves to theDotLottieinstance itself once the build is complete, allowing for chaining if needed.Example:
await dotlottie.build(); console.log("DotLottie archive built successfully.");
toArrayBuffer(): Promise<ArrayBuffer>
Asynchronously generates the .lottie archive as an ArrayBuffer. This is useful for saving to a file in Node.js or for transmitting the data.
Prerequisite:
build()must have been successfully called beforehand.Returns:
Promise<ArrayBuffer>- A promise that resolves to anArrayBuffercontaining the binary data of the.lottiefile.Example (Node.js):
// Assuming dotlottie instance is built const buffer = await dotlottie.toArrayBuffer(); // Now use Node.js 'fs' module to save the buffer to a file // import fs from 'fs'; // fs.writeFileSync('animation.lottie', Buffer.from(buffer));
toBlob(): Promise<Blob>
Asynchronously generates the .lottie archive as a Blob. This is primarily useful in browser environments, for example, to create an object URL for downloading or displaying.
Prerequisite:
build()must have been successfully called beforehand.Returns:
Promise<Blob>- A promise that resolves to aBlobobject representing the.lottiefile.Example (Browser):
// Assuming dotlottie instance is built const blob = await dotlottie.toBlob(); // const url = URL.createObjectURL(blob); // console.log('Blob URL:', url);
toBase64(): Promise<string>
Asynchronously generates the .lottie archive as a base64 encoded string.
Prerequisite:
build()must have been successfully called beforehand.Returns:
Promise<string>- A promise that resolves to a base64 string representation of the.lottiefile.Example:
// Assuming dotlottie instance is built const base64String = await dotlottie.toBase64(); // console.log('Base64 encoded .lottie:', base64String.substring(0, 100) + '...');
download(fileName: string): Promise<void>
Asynchronously triggers a browser download of the generated .lottie file with the specified filename. This method is intended for browser environments.
Prerequisite:
build()must have been successfully called beforehand.Parameters:
fileName:string- The desired filename for the downloaded file (e.g.,animation.lottie).
Returns:
Promise<void>- A promise that resolves when the download process has been initiated.Example (Browser):
// Assuming dotlottie instance is built try { await dotlottie.download("my_animation.lottie"); console.log("Download initiated."); } catch (error) { console.error("Download failed:", error); }
This concludes the API documentation for the DotLottie (V2) class.
Next up: DotLottieV1 Class