@lottiefiles/dotlottie-web
Version:
Lottie and DotLottie player for the web
2,227 lines • 81 kB
text/typescript
//#region src/core/dotlottie-player.d.ts
/**
* Playback direction / bounce mode.
*/
declare enum Mode$1 {
Forward = 0,
Reverse = 1,
Bounce = 2,
ReverseBounce = 3
}
/**
* Current status of the animation player.
*/
declare enum Status {
Idle = 0,
Playing = 1,
Paused = 2,
Stopped = 3,
Tweening = 4
}
declare class DotLottiePlayerWasm {
free(): void;
clear_slot(id: string): boolean;
layout_fit(): string;
loop_count(): number;
/**
* Poll the next player event. Returns `null` if the queue is empty,
* otherwise a plain JS object with a `type` string field and optional
* payload fields (`frameNo`, `loopCount`).
*/
poll_event(): any;
/**
* Reset a slot to its default value from the animation.
*/
reset_slot(id: string): boolean;
/**
* Set the layout.
*
* `fit` is one of `"contain"`, `"fill"`, `"cover"`, `"fit-width"`,
* `"fit-height"`, `"none"`. `align_x` / `align_y` are in [0, 1].
*/
set_layout(fit: string, align_x: number, align_y: number): boolean;
set_marker(name: string): void;
clear_slots(): boolean;
is_complete(): boolean;
/**
* Reset all slots to their default values from the animation.
*/
reset_slots(): boolean;
reset_theme(): boolean;
segment_end(): number;
set_quality(quality: number): boolean;
set_segment(start: number, end: number): boolean;
sm_set_seed(seed: bigint): boolean;
static unload_font(name: string): boolean;
animation_id(): string | undefined;
/**
* Returns the current global audio volume multiplier.
*/
audio_volume(): number;
background_a(): number;
background_b(): number;
background_g(): number;
background_r(): number;
clear_marker(): void;
emit_on_loop(): void;
/**
* Get all slot IDs as a JS array.
*/
get_slot_ids(): any;
/**
* Get the JSON value of a single slot by ID, or `undefined` if not found.
*/
get_slot_str(id: string): string | undefined;
/**
* Returns an array of marker name strings.
*/
marker_names(): any;
set_autoplay(v: boolean): void;
/**
* Set a single slot by ID from a JSON value string.
*/
set_slot_str(id: string, json: string): boolean;
set_viewport(x: number, y: number, w: number, h: number): boolean;
total_frames(): number;
clear_segment(): boolean;
current_frame(): number;
/**
* Get the type string of a slot, or `undefined` if not found.
*/
get_slot_type(id: string): string | undefined;
/**
* Get all slots as a JSON object string.
*/
get_slots_str(): string;
/**
* Returns the current affine transform as a flat `Float32Array`.
*/
get_transform(): Float32Array;
segment_start(): number;
/**
* Set multiple slots at once from a JSON string.
*/
set_slots_str(json: string): boolean;
set_text_slot(id: string, text: string): boolean;
set_transform(data: Float32Array): boolean;
/**
* Returns all state machine inputs as a JS array of strings.
*/
sm_get_inputs(): any;
/**
* Poll the next state machine event. Returns `null` if the queue is empty,
* otherwise a JS object with a `type` field and optional payload.
*/
sm_poll_event(): any;
sm_post_click(x: number, y: number): void;
/**
* `[width, height]` of the animation in its native coordinate space.
*/
animation_size(): Float32Array;
/**
* Name of the currently active marker, or `undefined` if none.
*/
current_marker(): string | undefined;
layout_align_x(): number;
layout_align_y(): number;
/**
* Load a Lottie JSON animation.
*
* `setup_target` must have been called first.
*/
load_animation(data: string): boolean;
loop_animation(): boolean;
/**
* Set background colour. Pass `(0, 0, 0, 0)` to clear.
*/
set_background(r: number, g: number, b: number, a: number): boolean;
/**
* Set a color slot (`r`, `g`, `b` in [0, 1]).
*/
set_color_slot(id: string, r: number, g: number, b: number): boolean;
/**
* Set an image slot from a source string (a `data:` URI, an `http(s)://`
* URL, or a file in the package `i/` folder referenced by name).
*/
set_image_slot(id: string, src: string): boolean;
set_loop_count(n: number): void;
set_theme_data(data: string): boolean;
sm_reset_input(key: string): void;
/**
* Returns the animation manifest as a JSON string, or empty string if unavailable.
*/
manifest_string(): string;
set_scalar_slot(id: string, value: number): boolean;
set_vector_slot(id: string, x: number, y: number): boolean;
/**
* Set up (or resize) the software rendering target.
*/
setup_sw_target(width: number, height: number): boolean;
/**
* Zero-copy `Uint8Array` view into WASM linear memory.
*
* **Use the returned array immediately.** Do not store the reference across
* any call that may reallocate the buffer (e.g. `resize` / `load_animation`
* with different dimensions).
*/
get_pixel_buffer(): Uint8Array;
/**
* Set the global audio volume multiplier (clamped to [0.0, 1.0]).
*/
set_audio_volume(volume: number): void;
/**
* Get the name of the current state.
*/
sm_current_state(): string;
/**
* Returns the ID of the currently active state machine, or `undefined`.
*/
state_machine_id(): string | undefined;
/**
* Returns the raw JSON definition of a state machine by ID, or `undefined`.
*/
get_state_machine(id: string): string | undefined;
set_position_slot(id: string, x: number, y: number): boolean;
current_loop_count(): number;
/**
* Set a resolver for assets outside the dotLottie container (remote URLs,
* external paths). Called synchronously with the asset `src` when ThorVG
* first needs it; return a `Uint8Array` with the bytes, or `null`/`undefined`
* to skip. Takes effect on the next load. Pass `null` to clear the resolver.
*/
set_asset_resolver(resolver?: Function | null): void;
/**
* Returns the framework setup listeners as a JS array of strings.
*/
sm_framework_setup(): any;
sm_post_pointer_up(x: number, y: number): void;
/**
* Load a state machine from a JSON definition string. Returns `true` on
* success. The engine is kept alive inside the player and interacted
* with via the `sm_*` methods.
*/
state_machine_load(definition: string): boolean;
/**
* Load a .lottie archive from raw bytes.
*
* `setup_target` must have been called first.
*/
load_dotlottie_data(data: Uint8Array): boolean;
sm_get_string_input(key: string): string | undefined;
sm_set_string_input(key: string, value: string): boolean;
sm_get_boolean_input(key: string): boolean | undefined;
sm_get_numeric_input(key: string): number | undefined;
sm_post_pointer_down(x: number, y: number): void;
sm_post_pointer_exit(x: number, y: number): void;
sm_post_pointer_move(x: number, y: number): void;
sm_set_boolean_input(key: string, value: boolean): boolean;
sm_set_numeric_input(key: string, value: number): boolean;
/**
* Unload the active state machine.
*/
state_machine_unload(): void;
sm_post_pointer_enter(x: number, y: number): void;
/**
* Load an animation from an already-loaded .lottie archive by its ID.
*
* `setup_target` must have been called first.
*/
load_animation_from_id(id: string): boolean;
/**
* Poll the next state machine internal event. Returns `null` if the
* queue is empty, otherwise a JS object `{ type: "Message", message }`.
*/
sm_poll_internal_event(): any;
use_frame_interpolation(): boolean;
reset_current_loop_count(): void;
/**
* Override the current state.
*/
sm_override_current_state(state: string, immediate: boolean): boolean;
/**
* Load a state machine from a .lottie archive by state-machine ID.
*/
state_machine_load_from_id(id: string): boolean;
set_use_frame_interpolation(v: boolean): void;
constructor();
mode(): Mode$1;
play(): boolean;
stop(): boolean;
/**
* Advance the animation by `dt` milliseconds and render if the frame changed.
* Call once per `requestAnimationFrame`, passing the frame delta in milliseconds.
*/
tick(dt: number): boolean;
pause(): boolean;
speed(): number;
width(): number;
height(): number;
/**
* Render the current frame without advancing time.
*/
render(): boolean;
status(): Status;
/**
* Returns an array of `{ name, start, end }` objects.
*/
markers(): any;
/**
* Fire a named event into the state machine.
*/
sm_fire(event: string): boolean;
/**
* Stop the state machine.
*/
sm_stop(): boolean;
/**
* Advance the state machine by `dt` milliseconds and render if the frame changed.
* Returns `true` when a new frame was rendered, `false` otherwise.
*/
sm_tick(dt: number): boolean;
autoplay(): boolean;
duration(): number;
set_loop(v: boolean): void;
set_mode(mode: Mode$1): void;
/**
* Start the state machine with an open-URL policy.
*/
sm_start(require_user_interaction: boolean, whitelist: any[]): boolean;
theme_id(): string | undefined;
load_font(name: string, data: Uint8Array): boolean;
set_frame(no: number): boolean;
set_speed(speed: number): void;
set_theme(id: string): boolean;
/**
* Get the current status of the state machine as a string.
*/
sm_status(): string;
}
//#endregion
//#region src/event-manager.d.ts
/**
* Represents the different types of events that can be dispatched.
*/
type EventType = 'complete' | 'frame' | 'load' | 'loadError' | 'renderError' | 'loop' | 'pause' | 'play' | 'stop' | 'destroy' | 'freeze' | 'unfreeze' | 'render' | 'ready' | 'stateMachineStart' | 'stateMachineStop' | 'stateMachineTransition' | 'stateMachineStateEntered' | 'stateMachineStateExit' | 'stateMachineCustomEvent' | 'stateMachineError' | 'stateMachineBooleanInputValueChange' | 'stateMachineNumericInputValueChange' | 'stateMachineStringInputValueChange' | 'stateMachineInputFired' | 'stateMachineInternalMessage';
/**
* Maps an event type string to its respective event interface.
*/
type EventByType<T extends EventType> = Extract<Event, {
type: T;
}>;
/**
* Base interface for all events.
*/
interface BaseEvent {
type: EventType;
}
interface RenderEvent extends BaseEvent {
currentFrame: number;
type: 'render';
}
interface FreezeEvent extends BaseEvent {
type: 'freeze';
}
interface UnfreezeEvent extends BaseEvent {
type: 'unfreeze';
}
interface DestroyEvent extends BaseEvent {
type: 'destroy';
}
/**
* Event fired when a loop action occurs.
*/
interface LoopEvent extends BaseEvent {
loopCount: number;
type: 'loop';
}
/**
* Event fired during frame changes.
*/
interface FrameEvent extends BaseEvent {
currentFrame: number;
type: 'frame';
}
/**
* Event fired when a load action occurs.
*/
interface LoadEvent extends BaseEvent {
type: 'load';
}
/**
* Event fired when a loading error occurs.
*/
interface LoadErrorEvent extends BaseEvent {
error: Error;
type: 'loadError';
}
/**
* Event fired when a loading error occurs.
*/
interface RenderErrorEvent extends BaseEvent {
error: Error;
type: 'renderError';
}
/**
* Event fired when a completion action occurs.
*/
interface CompleteEvent extends BaseEvent {
type: 'complete';
}
/**
* Event fired when a pause action occurs.
*/
interface PauseEvent extends BaseEvent {
type: 'pause';
}
/**
* Event fired when a play action occurs.
*/
interface PlayEvent extends BaseEvent {
type: 'play';
}
/**
* Event fired when a stop action occurs.
*/
interface StopEvent extends BaseEvent {
type: 'stop';
}
/**
* Event fired when a WASM module is initialized and ready.
*/
interface ReadyEvent extends BaseEvent {
type: 'ready';
}
interface StateMachineStartEvent extends BaseEvent {
type: 'stateMachineStart';
}
interface StateMachineStopEvent extends BaseEvent {
type: 'stateMachineStop';
}
interface StateMachineTransitionEvent extends BaseEvent {
fromState: string;
toState: string;
type: 'stateMachineTransition';
}
interface StateMachineStateEnteredEvent extends BaseEvent {
state: string;
type: 'stateMachineStateEntered';
}
interface StateMachineStateExitEvent extends BaseEvent {
state: string;
type: 'stateMachineStateExit';
}
interface StateMachineCustomEvent extends BaseEvent {
eventName: string;
type: 'stateMachineCustomEvent';
}
interface StateMachineErrorEvent extends BaseEvent {
error: string;
type: 'stateMachineError';
}
interface StateMachineBooleanInputValueChangeEvent extends BaseEvent {
inputName: string;
newValue: boolean;
oldValue: boolean;
type: 'stateMachineBooleanInputValueChange';
}
interface StateMachineNumericInputValueChangeEvent extends BaseEvent {
inputName: string;
newValue: number;
oldValue: number;
type: 'stateMachineNumericInputValueChange';
}
interface StateMachineStringInputValueChangeEvent extends BaseEvent {
inputName: string;
newValue: string;
oldValue: string;
type: 'stateMachineStringInputValueChange';
}
interface StateMachineInputFiredEvent extends BaseEvent {
inputName: string;
type: 'stateMachineInputFired';
}
interface StateMachineInternalMessage extends BaseEvent {
message: string;
type: 'stateMachineInternalMessage';
}
/**
* Type representing all possible event types.
*/
type Event = LoopEvent | FrameEvent | LoadEvent | LoadErrorEvent | RenderErrorEvent | CompleteEvent | PauseEvent | PlayEvent | StopEvent | DestroyEvent | FreezeEvent | UnfreezeEvent | RenderEvent | ReadyEvent | StateMachineStartEvent | StateMachineStopEvent | StateMachineTransitionEvent | StateMachineStateEnteredEvent | StateMachineStateExitEvent | StateMachineCustomEvent | StateMachineErrorEvent | StateMachineBooleanInputValueChangeEvent | StateMachineNumericInputValueChangeEvent | StateMachineStringInputValueChangeEvent | StateMachineInputFiredEvent | StateMachineInternalMessage;
type EventListener<T extends EventType> = (event: EventByType<T>) => void;
/**
* Manages registration and dispatching of event listeners.
*/
declare class EventManager {
private readonly _eventListeners;
addEventListener<T extends EventType>(type: T, listener: EventListener<T>): void;
removeEventListener<T extends EventType>(type: T, listener?: EventListener<T>): void;
dispatch<T extends EventType>(event: EventByType<T>): void;
removeAllEventListeners(): void;
}
//#endregion
//#region src/types.d.ts
/**
* 3x3 transformation matrix for the entire animation on the canvas.
* Represented as a flattened 9-element tuple in row-major order: [m00, m01, m02, m10, m11, m12, m20, m21, m22].
* Used for affine transformations (translation, rotation, scale, skew) applied to the whole animation.
*/
type Transform = [number, number, number, number, number, number, number, number, number];
/**
* Animation marker representing a named section within a Lottie animation.
*/
interface Marker {
name: string;
start: number;
end: number;
}
/**
* Configuration for canvas rendering behavior.
* Controls how the animation is rendered and when rendering is optimized.
*/
interface RenderConfig {
/**
* Automatically resize canvas when container size changes.
* Set to true to maintain responsiveness without manual resize calls.
*/
autoResize?: boolean;
/**
* Pixel density multiplier for high-DPI displays.
* Higher values increase quality but use more memory. Defaults to window.devicePixelRatio.
*/
devicePixelRatio?: number;
/**
* Pause rendering when canvas is outside the viewport.
* Set to true (default) to improve performance when animation isn't visible.
*/
freezeOnOffscreen?: boolean;
/**
* Rendering quality level (0-100).
* Lower values reduce quality but improve performance on resource-constrained devices.
*/
quality?: number;
}
/**
* Animation playback direction mode.
* Determines how frames are sequenced: forward, reverse, or alternating (bounce) modes.
*/
type Mode = 'forward' | 'reverse' | 'bounce' | 'reverse-bounce';
/**
* Animation data format accepted by the player.
* Can be a JSON string, binary ArrayBuffer, or parsed JSON object.
*/
type Data = string | ArrayBuffer | Record<string, unknown>;
/**
* Layout fit mode determining how animation scales to canvas.
* Controls scaling behavior similar to CSS object-fit property.
*/
type Fit = 'contain' | 'cover' | 'fill' | 'none' | 'fit-width' | 'fit-height';
/**
* Layout configuration for positioning and scaling animations within the canvas.
* Determines how the animation fits and aligns within the available space.
*/
interface Layout {
/**
* Alignment position as [x, y] coordinates in 0-1 range.
* [0.5, 0.5] centers the animation, [0, 0] is top-left, [1, 1] is bottom-right.
*/
align?: [number, number];
/**
* Fit mode controlling how animation scales to canvas dimensions.
* Defaults to 'contain' to show the full animation without cropping.
*/
fit?: Fit;
}
/**
* Dimensions of a rendering surface for custom canvas implementations.
* Used when providing a custom render surface instead of HTMLCanvasElement.
*/
interface RenderSurface {
/** Height of the render surface in pixels */
height: number;
/** Width of the render surface in pixels */
width: number;
}
/**
* Resolves an asset the animation references but does not embed.
* Called synchronously while the animation loads, so the bytes must already be in memory.
* @param src - The asset path as referenced by the animation, e.g. `/images/img_0.png`
* @returns The asset bytes, or `null`/`undefined` to leave the asset unresolved
*/
type AssetResolver = (src: string) => ArrayBuffer | Uint8Array | null | undefined;
/**
* Main configuration object for initializing a DotLottie player.
* Specifies the animation source, playback behavior, rendering options, and canvas target.
*/
interface Config {
/**
* ID of the specific animation to play from a multi-animation dotLottie file.
* Leave undefined for single-animation files or to play the default animation.
*/
animationId?: string;
/**
* Resolves assets the animation references but does not embed.
* `load()` reconfigures from its config, so pass it on every `load()` that needs it.
*/
assetResolver?: AssetResolver;
/**
* Automatically start playback once the animation is loaded.
* Set to true for animations that should play immediately without user interaction.
*/
autoplay?: boolean;
/**
* Background color as a CSS color string (e.g., '#FFFFFF' or 'transparent').
* Applied to the canvas element or as a fill behind the animation.
*/
backgroundColor?: string;
/**
* Target canvas element for rendering.
* Can be HTMLCanvasElement, OffscreenCanvas, or custom RenderSurface with dimensions.
*/
canvas?: HTMLCanvasElement | OffscreenCanvas | RenderSurface;
/**
* Animation data to load directly.
* Use this to load from a string, ArrayBuffer, or parsed JSON instead of fetching from src.
*/
data?: Data;
/**
* Layout configuration for positioning and scaling the animation.
* Controls fit mode and alignment within the canvas.
*/
layout?: Layout;
/**
* Enable continuous looping of the animation.
* Set to true to repeat indefinitely, or use loopCount for a specific number of loops.
*/
loop?: boolean;
/**
* Number of additional times to replay the animation after the first play.
* Requires `loop` to be true. A value of 0 means infinite replays; a positive value `n` means
* the animation plays a total of `n + 1` times (initial play + `n` replays).
*/
loopCount?: number;
/**
* Named marker to use as the playback segment.
* Plays only the portion of the animation defined by this marker instead of the full animation.
*/
marker?: string;
/**
* Playback direction mode.
* Controls whether animation plays forward, reverse, or alternates (bounce).
*/
mode?: Mode;
/**
* Rendering configuration controlling canvas behavior.
* Includes autoResize, devicePixelRatio, freezeOnOffscreen, and quality settings.
*/
renderConfig?: RenderConfig;
/**
* Frame range to play as [startFrame, endFrame].
* Restricts playback to a specific portion of the animation instead of the full sequence.
*/
segment?: [number, number];
/**
* Playback speed multiplier.
* 1 is normal speed, 2 is double speed, 0.5 is half speed.
*/
speed?: number;
/**
* Audio volume for animations with sound, from 0 (muted) to 1 (full).
* Defaults to 1.
*/
volume?: number;
/**
* URL to fetch the animation from.
* Use this to load .lottie or .json files from a remote or local path.
*/
src?: string;
/**
* State machine security configuration.
* Controls URL opening policies for state machine-driven animations.
*/
stateMachineConfig?: StateMachineConfig;
/**
* ID of the state machine to load and activate.
* State machines enable interactive, event-driven animation behaviors.
*/
stateMachineId?: string;
/**
* ID of the theme to apply to the animation.
* Themes modify colors and visual properties defined in the dotLottie manifest.
*/
themeId?: string;
/**
* Enable frame interpolation for smoother playback.
* Set to true (default) for smoother animation, false for exact frame-by-frame playback.
*/
useFrameInterpolation?: boolean;
}
interface WebGLConfig extends Omit<Config, 'canvas'> {
canvas: HTMLCanvasElement;
}
interface WebGPUConfig extends Omit<Config, 'canvas'> {
canvas: HTMLCanvasElement;
device?: GPUDevice;
}
interface StateMachineConfig {
/**
* Controls whether and which URLs can be opened by a state machine.
*
* - requireUserInteraction: When true, URLs open only after an explicit user action
* (e.g., click/pointer down) on the animation.
* - whitelist: List of allowed URL patterns. An empty list blocks all URLs. Use
* "*" to allow all URLs. Wildcards are supported in host and path (e.g.,
* "*.example.com/*").
*
* @example
* ```typescript
* // Require user interaction before opening any URL
* openUrlPolicy: { requireUserInteraction: true, whitelist: ["*"] }
*
* // Block all URLs
* openUrlPolicy: { whitelist: [] }
*
* // Allow all URLs
* openUrlPolicy: { whitelist: ["*"] }
*
* // Allow a specific domain only
* openUrlPolicy: { whitelist: ["https://example.com"] }
*
* // Allow subdomains and any path under lottiefiles.com
* openUrlPolicy: { whitelist: ["*.lottiefiles.com/*"] }
* ```
*
* By default, URLs are denied and require user interaction.
*/
openUrlPolicy?: {
requireUserInteraction?: boolean;
whitelist?: string[];
};
}
/**
* dotLottie manifest containing metadata about available animations, themes, and state machines.
* Included in .lottie files to describe the contents and relationships between components.
*/
interface Manifest {
/**
* List of animations available in this dotLottie file.
* Each animation can have its own ID, themes, and background color.
*/
animations: Array<{
/** Background color for this animation */background?: string; /** Unique identifier for this animation */
id: string; /** Default theme to apply when this animation loads */
initialTheme?: string; /** List of theme IDs compatible with this animation */
themes?: string[];
}>;
/** Tool or application that created this dotLottie file */
generator?: string;
/** List of available state machines for interactive behavior */
stateMachines?: Array<{
id: string;
}>;
/** List of available themes that can modify animation appearance */
themes?: Array<{
id: string;
}>;
/** dotLottie specification version */
version?: string;
}
/**
* Bezier easing handle for keyframe interpolation
*/
interface BezierHandle {
x: number | number[];
y: number | number[];
}
/**
* Keyframe in Lottie native format
* The value type (Color, Vector, number, etc.)
*/
interface Keyframe<T> {
/** Hold keyframe - no interpolation to next keyframe */
h?: 0 | 1;
/** Incoming bezier handle (optional, for easing) */
i?: BezierHandle;
/** Outgoing bezier handle (optional, for easing) */
o?: BezierHandle;
/** Start value at this keyframe */
s: T;
/** Time (frame number) */
t: number;
}
/**
* Color as RGB or RGBA array with values normalized to [0, 1]
* @example [1, 0, 0] // red
* @example [1, 0, 0, 0.5] // red with 50% opacity
*/
type Color = [number, number, number] | [number, number, number, number];
/**
* Color slot value - static color or array of keyframes
* @example Static: [1, 0, 0, 1] // red
* @example Animated: [\{ t: 0, s: [1, 0, 0, 1] \}, \{ t: 60, s: [0, 0, 1, 1] \}]
*/
type ColorSlotValue = Color | Array<Keyframe<Color>>;
/**
* Scalar slot value - static number or array of keyframes (rotation, opacity, etc.)
* @example Static: 45
* @example Animated: [\{ t: 0, s: 0 \}, \{ t: 60, s: 360 \}]
*/
type ScalarSlotValue = number | Array<Keyframe<number>>;
/**
* Vector as 2D or 3D point
* @example [100, 100] // 2D vector
* @example [100, 100, 0] // 3D vector
*/
type Vector = [number, number] | [number, number, number];
/**
* Vector slot value - static vector or array of keyframes
* Used for both "vector" and "position" slot types
* @example Static: [100, 100]
* @example Animated: [\{ t: 0, s: [0, 0] \}, \{ t: 60, s: [100, 100] \}]
*/
type VectorSlotValue = Vector | Array<Keyframe<Vector>>;
/**
* Gradient as raw Lottie flat array format.
* Color stops (4 floats each): [offset, r, g, b, offset, r, g, b, ...]
* Opacity stops (2 floats each, appended after color stops): [...color stops, offset, alpha, offset, alpha, ...]
* All values are in [0, 1] range.
* Expected array size: 4 * colorStopCount + 2 * opacityStopCount
* @example Without opacity: [0, 1, 0, 0, 1, 0, 0, 1] // red to blue gradient (2 color stops)
* @example With opacity: [0, 1, 0, 0, 1, 0, 0, 1, 0, 0.8, 1, 1] // red to blue, 80% -> 100% opacity
*/
type Gradient = number[];
/**
* Gradient slot value - static gradient or array of keyframes
* @example Static without opacity: [0, 1, 0, 0, 1, 0, 0, 1]
* @example Static with opacity: [0, 1, 0, 0, 1, 0, 0, 1, 0, 0.8, 1, 1]
* @example Animated: [\{ t: 0, s: [0, 1, 0, 0, 1, 0, 0, 1] \}]
*/
type GradientSlotValue = Gradient | Array<Keyframe<Gradient>>;
/**
* Text document properties
* @see https://lottiefiles.github.io/lottie-docs/text/#text-document
*/
interface TextDocument {
/** Font family */
f?: string;
/** Fill color [r, g, b] or [r, g, b, a] in [0, 1] range */
fc?: Color;
/** Justify: 0=left, 1=right, 2=center */
j?: 0 | 1 | 2;
/** Line height */
lh?: number;
/** Font size */
s?: number;
/** Stroke color [r, g, b] or [r, g, b, a] in [0, 1] range */
sc?: Color;
/** Stroke width */
sw?: number;
/** Text content (newlines encoded with carriage return) */
t?: string;
/** Tracking (letter spacing) */
tr?: number;
}
/**
* Text slot value - always static (text documents don't support animation)
* @example \{ t: 'Hello', s: 24, fc: [0,0,0,1] \}
*/
type TextSlotValue = TextDocument;
/**
* Slot type string as returned by the core
*/
type SlotType = 'color' | 'gradient' | 'image' | 'text' | 'scalar' | 'vector';
/**
* Base properties shared by all theme keyframes.
*/
interface ThemeBaseKeyframe {
/** Timeline position in animation frames */
frame: number;
/** When true, holds value without interpolation until next keyframe */
hold?: boolean;
/** Incoming Bézier handle for easing into this keyframe */
inTangent?: BezierHandle;
/** Outgoing Bézier handle for easing out of this keyframe */
outTangent?: BezierHandle;
}
/**
* Color keyframe for animated color transitions.
*/
interface ThemeColorKeyframe extends ThemeBaseKeyframe {
/** Color value as normalized RGB or RGBA (0-1 range) */
value: Color;
}
/**
* Scalar keyframe for animated numeric properties.
*/
interface ThemeScalarKeyframe extends ThemeBaseKeyframe {
/** Numeric value at this keyframe */
value: number;
}
/**
* Position keyframe for animated position properties.
*/
interface ThemePositionKeyframe extends ThemeBaseKeyframe {
/** Position as 2D or 3D coordinates */
value: Vector;
/** Incoming tangent for spatial interpolation (curved paths) */
valueInTangent?: number[];
/** Outgoing tangent for spatial interpolation (curved paths) */
valueOutTangent?: number[];
}
/**
* Vector keyframe for animated vector properties (scale, size, etc.).
*/
interface ThemeVectorKeyframe extends ThemeBaseKeyframe {
/** Vector value as [x, y] or [x, y, z] */
value: Vector;
}
/**
* Gradient color stop definition.
*/
interface ThemeGradientStop {
/** Color as RGB or RGBA (0-1 range) */
color: Color;
/** Position along gradient line (0-1) */
offset: number;
}
/**
* Gradient keyframe for animated gradient transitions.
*/
interface ThemeGradientKeyframe extends ThemeBaseKeyframe {
/** Array of gradient stops at this keyframe */
value: ThemeGradientStop[];
}
/**
* Text justification options.
*/
type ThemeTextJustify = 'Left' | 'Right' | 'Center' | 'JustifyLastLeft' | 'JustifyLastRight' | 'JustifyLastCenter' | 'JustifyLastFull';
/**
* Text capitalization styles.
*/
type ThemeTextCaps = 'Regular' | 'AllCaps' | 'SmallCaps';
/**
* Text document properties for theme text rules.
* Uses descriptive property names as per dotLottie v2.0 spec.
* @see https://dotlottie.io/spec/2.0/#text-document
*/
interface ThemeTextDocument {
/** Vertical baseline offset in pixels */
baselineShift?: number;
/** Fill color as RGB or RGBA (0-1 range) */
fillColor?: Color;
/** Font family name */
fontName?: string;
/** Font size in points */
fontSize?: number;
/** Text alignment and justification */
justify?: ThemeTextJustify;
/** Line height spacing multiplier */
lineHeight?: number;
/** Stroke color as RGB or RGBA (0-1 range) */
strokeColor?: Color;
/** When true, stroke renders over fill */
strokeOverFill?: boolean;
/** Stroke width in pixels */
strokeWidth?: number;
/** Text content to display */
text?: string;
/** Text capitalization style */
textCaps?: ThemeTextCaps;
/** Letter spacing in 1/1000 em units */
tracking?: number;
/** Text wrap box position [x, y] */
wrapPosition?: [number, number];
/** Text wrap bounding box [width, height] */
wrapSize?: [number, number];
}
/**
* Text keyframe for animated text document properties.
*/
interface ThemeTextKeyframe {
/** Timeline position in animation frames */
frame: number;
/** Text document configuration at this keyframe */
value: ThemeTextDocument;
}
/**
* Image value for theme image rules.
*/
interface ThemeImageValue {
/** Display height in pixels */
height?: number;
/** Reference to image in dotLottie package (i/ folder) */
id?: string;
/** External URL or data URI (fallback if id not found) */
url?: string;
/** Display width in pixels */
width?: number;
}
/**
* Base properties shared by all theme rules.
*/
interface ThemeBaseRule {
/** Limit rule to specific animations (omit to apply to all) */
animations?: string[];
/** Lottie expression for dynamic values */
expression?: string;
/** Slot ID in the Lottie animation (case-sensitive) */
id: string;
}
/**
* Color rule for overriding color properties (fill, stroke, text color).
*/
interface ThemeColorRule extends ThemeBaseRule {
/** Animated color keyframes */
keyframes?: ThemeColorKeyframe[];
type: 'Color';
/** Static color value (RGB or RGBA, 0-1 range) */
value?: Color;
}
/**
* Scalar rule for overriding numeric properties (opacity, stroke width, rotation).
*/
interface ThemeScalarRule extends ThemeBaseRule {
/** Animated scalar keyframes */
keyframes?: ThemeScalarKeyframe[];
type: 'Scalar';
/** Static numeric value */
value?: number;
}
/**
* Position rule for overriding position properties.
*/
interface ThemePositionRule extends ThemeBaseRule {
/** Animated position keyframes */
keyframes?: ThemePositionKeyframe[];
type: 'Position';
/** Static position (2D or 3D coordinates) */
value?: Vector;
}
/**
* Vector rule for overriding vector properties (scale, size).
*/
interface ThemeVectorRule extends ThemeBaseRule {
/** Animated vector keyframes */
keyframes?: ThemeVectorKeyframe[];
type: 'Vector';
/** Static vector value */
value?: Vector;
}
/**
* Gradient rule for overriding gradient properties.
*/
interface ThemeGradientRule extends ThemeBaseRule {
/** Animated gradient keyframes */
keyframes?: ThemeGradientKeyframe[];
type: 'Gradient';
/** Static gradient (array of color stops) */
value?: ThemeGradientStop[];
}
/**
* Image rule for overriding image assets.
*/
interface ThemeImageRule extends ThemeBaseRule {
type: 'Image';
/** Image replacement configuration (required for Image rules) */
value: ThemeImageValue;
}
/**
* Text rule for overriding text document properties.
*/
interface ThemeTextRule extends ThemeBaseRule {
/** Animated text keyframes */
keyframes?: ThemeTextKeyframe[];
type: 'Text';
/** Static text document configuration */
value?: ThemeTextDocument;
}
/**
* Union of all theme rule types.
*/
type ThemeRule = ThemeColorRule | ThemeScalarRule | ThemePositionRule | ThemeVectorRule | ThemeGradientRule | ThemeImageRule | ThemeTextRule;
/**
* Theme definition for customizing Lottie animation properties.
* Themes override animated properties mapped to Lottie Slots.
* @see https://dotlottie.io/spec/2.0/#themes
*
* @example
* ```typescript
* const theme: Theme = {
* rules: [
* {
* id: 'background_color',
* type: 'Color',
* value: [0.2, 0.4, 0.8] // Blue
* },
* {
* id: 'title_text',
* type: 'Text',
* value: {
* text: 'Hello World',
* fontSize: 48,
* fillColor: [1, 1, 1]
* }
* }
* ]
* };
*
* dotLottie.setThemeData(theme);
* ```
*/
interface Theme {
/** Array of rules defining property overrides */
rules: ThemeRule[];
}
//#endregion
//#region src/dotlottie.d.ts
declare class DotLottie {
protected _canvas: HTMLCanvasElement | OffscreenCanvas | RenderSurface | null;
private _pendingLoad;
private _srcFetchAbort;
protected _context: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D | null;
private readonly _eventManager;
private _animationFrameId;
private readonly _frameManager;
private readonly _boundAnimationLoop;
protected _dotLottieCore: DotLottiePlayerWasm | null;
private _stateMachineId;
private _themeId;
private _animationId;
private _stateMachineConfig;
private _isStateMachineRunning;
protected _renderConfig: RenderConfig;
private _isFrozen;
private _backgroundColor;
private _volume;
private _lastFrameTime;
private _boundOnClick;
private _boundOnPointerUp;
private _boundOnPointerDown;
private _boundOnPointerMove;
private _boundOnPointerEnter;
private _boundOnPointerLeave;
private _bufferMismatchCount;
private _lastExpectedBufferSize;
private _cachedImageData;
private _cachedImageDataBuffer;
private _cachedImageDataByteOffset;
private _marker;
private _segment;
/**
* Creates a new DotLottie player instance for rendering Lottie animations.
* Initializes the WASM module, event system, and loads animation if src or data is provided in config.
* @param config - Configuration object specifying animation source, playback settings, and rendering options
*/
constructor(config: Config);
protected _initWasm(): Promise<void>;
protected _createCore(): DotLottiePlayerWasm;
protected _onCoreCreated(): void;
protected _setupTarget(width: number, height: number): boolean;
private _drainPlayerEvents;
private _discardPlayerEvents;
private _drainSmEvents;
private _dispatchError;
private _fetchData;
private _loadFromData;
private _loadFromSrc;
/**
* Gets the raw pixel buffer containing the rendered animation frame.
* Returns RGBA pixel data as a Uint8Array for advanced image processing or custom rendering.
*/
get buffer(): Uint8Array | null;
/**
* Gets the ID of the currently active animation from a multi-animation dotLottie file.
* Returns undefined if no specific animation is active or for single-animation files.
*/
get activeAnimationId(): string | undefined;
/**
* Gets the ID of the currently active theme applied to the animation.
* Returns undefined if no theme is active. Themes modify colors and visual properties.
*/
get activeThemeId(): string | undefined;
/**
* Gets the current layout configuration for positioning and scaling the animation.
* Includes fit mode (contain, cover, fill, etc.) and alignment [x, y] values (0-1 range).
*/
get layout(): Layout | undefined;
/**
* Gets the currently active marker name if a marker-based segment is set.
* Returns undefined if no marker is active. Use setMarker() to activate a named segment.
*/
get marker(): string | undefined;
/**
* Gets the animation manifest containing metadata about animations, themes, and states.
* Returns null if no manifest is available or if the loaded animation doesn't include one.
*/
get manifest(): Manifest | null;
/**
* Gets the current rendering configuration.
* Includes settings like devicePixelRatio, autoResize, and freezeOnOffscreen.
*/
get renderConfig(): RenderConfig;
/**
* Gets the currently active playback segment as [startFrame, endFrame].
* Returns the effective segment from the WASM core. When no custom segment is set,
* returns [0, totalFrames - 1] (full animation range). Returns undefined only when the core is not loaded.
*/
get segment(): [number, number] | undefined;
/**
* Gets the current loop configuration.
* Returns true if the animation is set to loop continuously.
*/
get loop(): boolean;
/**
* Gets the current playback mode.
* Determines playback direction: 'forward', 'reverse', 'bounce' (forward then reverse), or 'reverse-bounce'.
*/
get mode(): Mode;
/**
* Indicates whether rendering is currently frozen.
* True when freeze() has been called and the rendering loop is paused to save resources.
*/
get isFrozen(): boolean;
/**
* Indicates whether a state machine is currently active and running.
* True after stateMachineStart() is called and until stateMachineStop() is called.
*/
get isStateMachineRunning(): boolean;
/**
* Gets the current background color.
* Returns the background color as a string (e.g., '#FFFFFF' or 'transparent').
*/
get backgroundColor(): string;
/**
* Gets the autoplay configuration.
* Returns true if the animation is configured to start playing automatically when loaded.
*/
get autoplay(): boolean;
/**
* Gets the frame interpolation setting.
* Returns true if frame interpolation is enabled for smoother animation playback.
*/
get useFrameInterpolation(): boolean;
/**
* Gets the current playback speed.
* Returns the speed multiplier (1 = normal speed, 2 = double speed, 0.5 = half speed).
*/
get speed(): number;
/**
* Gets the audio volume, from 0 (muted) to 1 (full).
*/
get volume(): number;
/**
* Indicates whether the WASM module and core player have been initialized.
* Check this before performing operations that require the player to be ready.
*/
get isReady(): boolean;
/**
* Indicates whether an animation has been successfully loaded and is ready for playback.
* Check this before calling play() or other playback methods to ensure the animation is ready.
*/
get isLoaded(): boolean;
/**
* Indicates whether the animation is currently playing.
* True when animation is actively playing, false when paused, stopped, or not started.
*/
get isPlaying(): boolean;
/**
* Indicates whether the animation is currently paused.
* True when pause() has been called and animation is not playing or stopped.
*/
get isPaused(): boolean;
/**
* Indicates whether the animation is currently stopped.
* True when stop() has been called or animation hasn't started yet.
*/
get isStopped(): boolean;
/**
* Gets the current frame number of the animation.
* Useful for tracking playback position or implementing custom frame displays. Rounded to 2 decimal places.
*/
get currentFrame(): number;
/**
* Gets the number of times the animation has completed a loop during the current playback.
* Increments each time the animation completes one full cycle.
*/
get loopCount(): number;
/**
* Gets the total number of frames in the animation.
* Use with currentFrame to calculate playback progress as a percentage.
*/
get totalFrames(): number;
/**
* Gets the total duration of the animation in seconds.
* Represents the time to play from the first frame to the last at normal speed (speed = 1).
*/
get duration(): number;
/**
* Gets the canvas element used for rendering the animation.
* Returns the HTMLCanvasElement, OffscreenCanvas, or RenderSurface set during initialization.
*/
get canvas(): HTMLCanvasElement | OffscreenCanvas | RenderSurface | null;
/**
* Dynamically loads a new animation, replacing the current one if any.
* Stops current playback, cleans up resources, and loads from the provided src or data.
* @param config - Configuration for the new animation (all Config properties except canvas)
*/
load(config: Omit<Config, 'canvas'>): void;
protected _draw(): void;
private _cleanupCanvas;
private _initializeCanvas;
protected _setupRendererOnCanvas(): void;
private _stopAnimationLoop;
private _startAnimationLoop;
private _animationLoop;
/**
* Starts or resumes animation playback from the current frame.
* Unfreezes rendering if frozen and starts the animation loop. Updates isPlaying state to true.
*/
play(): void;
/**
* Pauses animation playback at the current frame.
* Stops the animation loop while preserving the current frame position. Updates isPaused state to true.
*/
pause(): void;
/**
* Stops animation playback and resets to the start frame.
* Halts the animation loop and returns to the beginning. Updates isStopped state to true.
*/
stop(): void;
/**
* Seeks to a specific frame in the animation and renders it.
* Useful for implementing custom scrubbing controls or precise frame positioning.
* @param frame - The target frame number to seek to
*/
setFrame(frame: number): void;
/**
* Changes the animation playback speed.
* Values above 1 speed up playback, below 1 slow it down.
* @param speed - Playback speed multiplier (e.g., 2 for 2x speed, 0.5 for half speed)
*/
setSpeed(speed: number): void;
/**
* Sets the audio volume for animations with sound. Kept across loads.
* @param volume - From 0 (muted) to 1 (full); values outside are clamped
*/
setVolume(volume: number): void;
/**
* Changes the background color of the canvas or animation.
* For HTMLCanvasElement, sets the CSS background. For other surfaces, renders behind the animation.
* @param color - CSS color string (e.g., '#FFFFFF', 'rgba(0,0,0,0.5)', 'transparent')
*/
setBackgroundColor(color: string): void;
/**
* Enables or disables continuous looping of the animation.
* When enabled with loopCount set to 0, animation repeats indefinitely.
* @param loop - True to enable looping, false to play once
*/
setLoop(loop: boolean): void;
/**
* Sets the number of additional times to replay the animation after the first play.
* Requires loop to be true. A value of 0 means infinite replays; a positive value n means
* the animation plays a total of n + 1 times (initial play + n replays).
* @param loopCount - Number of additional replays (0 = infinite, 1 = plays twice, 2 = plays three times, etc.)
*/
setLoopCount(loopCount: number): void;
/**
* Enables or disables frame interpolation for smoother playback.
* When enabled, interpolates between frames. When disabled, shows exact frame-by-frame animation.
* @param useFrameInterpolation - True for smooth interpolation, false for exact frames
*/
setUseFrameInterpolation(useFrameInterpolation: boolean): void;
/**
* Hands the resolver to the core, wrapped so a throw is logged and leaves the asset unresolved.
* @param resolver - The resolver, or null to clear it
*/
private _applyAssetResolver;
/**
* Subscribes to animation events like play, pause, frame, complete, etc.
* Use this to react to animation state changes and playback progress.
* @param type - Event type to listen for (e.g., 'play', 'frame', 'complete')
* @param listener - Callback function invoked when the event occurs
*/
addEventListener<T extends EventType>(type: T, listener: EventListener<T>): void;
/**
* Unsubscribes from animation events.
* If no listener is provided, removes all listeners for the given event type.
* @param type - Event type to stop listening for
* @param listener - Specific callback to remove, or undefined to remove all
*/
removeEventListener<T extends EventType>(type: T, listener?: EventListener<T>): void;
/**
* Cleans up and destroys the player instance, releasing all resources.
* Stops playback, removes event listeners, and frees WASM memory. Call when the player is no longer needed.
*/
destroy(): void;
/**
* Pauses the rendering loop without changing playback state.
* Useful for reducing CPU/GPU usage when the animation is offscreen or hidden. Dispatches 'freeze' event.
*/
freeze(): void;
/**
* Resumes the rendering loop after being frozen.
* Restarts frame rendering while maintaining the current playback state. Dispatches 'unfreeze' event.
*/
unfreeze(): void;
/**
* Recalculates and updates canvas dimensions based on current size.
* Call this when the canvas container size changes to maintain proper rendering. Usually handled by autoResize.
*/
private _syncCanvasSize;
resize(): void;
/**
* Changes the canvas element used for rendering.
* Useful for moving the animation to a different canvas without recreating the player instance.
* @param canvas - New HTMLCanvasElement, OffscreenCanvas, or RenderSurface to render to
*/
setCanvas(canvas: HTMLCanvasElement | OffscreenCanvas | RenderSurface): void;
/**
* Applies a 3x3 transformation matrix to the entire animation on the canvas.
* Use this to translate, rotate, scale, or skew the animation rendering.
* @param transform - 9-element array representing the transformation matrix in row-major order
* @returns True if transformation was applied successfully, false otherwise
*/
setTransform(transform: Transform): boolean;
/**
* Gets the 3x3 transformation matrix applied to the animation.
* Returns a 9-element array representing affine transformations (translation, rotation, scale, skew).
* @returns Transform array of 9 numbers, or undefined if not available
*/
getTransform(): Transform | undefined;
/**
* Sets a frame range to play instead of the full animation.
* Useful for playing specific sections or creating animation sequences from subsections.
* @param startFrame - Starting frame number (inclusive)
* @param endFrame - Ending frame number (inclusive)
*/
setSegment(startFrame: number, endFrame: number): void;
/**
* Clears the user-defined segment, restoring playback to the full animation range [0, totalFrames - 1].
*/
resetSegment(): void;
/**
* Changes the playback direction mode.
* Controls whether animation plays forward, in reverse, or alternates (bounce).
* @param mode - Playback mode: 'forward', 'reverse', 'bounce', or 'reverse-bounce'
*/
setMode(mode: Mode): void;
/**
* Updates rendering configuration like autoResize, devicePixelRatio, and freezeOnOffscreen.
* Dynamically changes how the canvas behaves without reloading the animation.
* @param config - Partial RenderConfig with properties to update
*/
setRenderConfig(config: RenderConfig): void;
/**
* Switches to a different animation within a multi-animation dotLottie file.
* Use this to load a different animation by its ID without creating a new player instance.
* @param animationId - ID of the animation to load (must exist in the manifest)
*/
loadAnimation(animationId: string): void;
/**
* Activates a named marker to play only that marked segment.
* Markers define named sections within an animation. Use markers() to list available markers.
* @param marker - Name of the marker to activate
*/
setMarker(marker: string): void;
/**
* Gets all markers defined in the animation with their start and end frames.
* Markers represent named sections that can be played using setMarker().
* @returns Array of marker objects with name, start, and end properties
*/
markers(): Marker[];
/**
* Applies a theme to the animation, modifying colors and visual properties.
* Themes are predefined in the dotLottie manifest. Returns true if theme was successfully loaded.
* @param themeId - ID of the theme to apply (must exist in manifest)
* @returns True if theme loaded successfully, false otherwise
*/
setTheme(themeId: string): boolean;
/**
* Removes the currently applied theme and restores original animation colors.
* Use this to revert to the default appearance after applying a theme.
* @returns True if theme was reset successfully, false otherwise
*/
resetTheme(): boolean;
/**
* Applies a custom theme from theme data instead of manifest theme ID.
* Useful for dynamically generated or user-created themes not in the manifest.
*
* @param themeData - Theme data as a JSON string or a structured Theme object
* @returns True if theme loaded successfully, false otherwise
*/
setThemeData(themeData: Theme | string): boolean;
/**
* Sets multiple slot values at once for parameterized animations.
* Slots allow runtime customization of colors, text, images, or other properties.
* @param slots - Object mapping slot IDs to their values
*/
setSlots(slots: Record<string, unknown>): void;
/**
* Check if value is an array of keyframes (has objects with 't' and 's' properties)
*/
private _isKeyframeArray;
/**
* Get all slot IDs in the animation
* @returns Array of slot ID strings
*/
getSlotIds(): string[];
/**
* Get the type of a slot
* @param slotId - The slot ID to query
* @returns The slot type ('color', 'gradient', 'text', 'scalar', 'vector', 'position', 'image') or undefined
*/
getSlotType(slotId: string): SlotType | undefined;
/**
* Get the current value of a slot
* @param slotId - The slot ID to query
* @returns The parsed slot value or undefined if not found
*/
getSlot(slotId: string): unknown;
/**
* Get all slots as an object with slot IDs as keys
* @returns Object containing all slots, or empty object if not loaded
*/
getSlots(): Record<string, unknown>;
/**
* Set a color slot value
* @param slotId - The slot ID to set
* @param value - Static color [r, g, b, a] or array of keyframes
* @returns true if successful
*/
setColorSlot(slotId: string, value: ColorSlotValue): boolean;
/**
* Set a scalar slot value (single number like rotation, opacity)
* @param slotId - The slot ID to set
* @param value - Static number or array of keyframes
* @returns true if successful
*/
setScalarSlot(slotId: string, value: ScalarSlotValue): boolean;
/**
* Set a vector slot value (2D or 3D point for position, scale, etc.)
* Handles both "vector" and "position" slot types
* @param slotId - The slot ID to set
* @param value - Static vector [x, y] or array of keyframes
* @returns true if successful
*/
setVectorSlot(slotId: string, value: VectorSlotValue): boolean;
/**
* Set a gradient slot value
* @param slotId - The slot ID to set
* @param value - Static gradient or array of keyframes
* @param colorStopCount - Number of color stops
* @returns true if successful
*/
setGradientSlot(slotId: string, value: GradientSlotValue, colorStopCount: number): boolean;
/**
* Set a text slot value (always static - text documents don't support animation)
* Supports partial updates - only provided properties will be changed, others inherit from existing value
* @param slotId - The slot ID to set
* @param value - Text document properties (partial allowed)
* @returns true if successful
*/
setTextSlot(slotId: string, value: TextSlotValue): boolean;
/**
* Set an image slot to a custom source.
*
* The WASM renderer can only decode embedded images, so `http(s)://` URLs are fetched
* and inlined as a `data:` URI before being handed to the core. `data:` URIs and
* package-relative file names are passed through unchanged.
* @param slotId - The image slot ID to set
* @param src - The image source: a `data:` URI, an `http(s)://` URL, or a package `i/` file name
* @returns true if successful
*/
setImageSlot(slotId: string, src: string): Promise<boolean>;
/**
* Reset a slot to its original value
* @param slotId - The slot ID to reset
* @returns true if successful
*/
resetSlot(slotId: string): boolean;
/**
* Clear a slot's custom value
* @param slotId - The slot ID to clear
* @returns true if successful
*/
clearSlot(slotId: string): boolean;
/**
* Reset all slots to their original values
* @returns true if successful
*/
resetSlots(): boolean;
/**
* Clear all slot custom values
* @returns true if successful
*/
clearSlots(): boolean;
/**
* Updates the layout configuration for positioning and scaling the animation.
* Changes how the animation fits and aligns within the canvas without requiring a reload.
* @param layout - New layout configuration with fit mode and alignment values
*/
setLayout(layout: Layout): void;
/**
* Sets a custom viewport region for rendering a portion of the animation.
* Defines a rectangular area to render, useful for implementing animation clipping or panning effects.
* @param x - X coordinate of the viewport's top-left corner
* @param y - Y coordinate of the viewport's top-left corner
* @param width - Width of the viewport in pixels
* @param height - Height of the viewport in pixels
* @returns True if viewport was set successfully, false otherwise
*/
setViewport(x: number, y: number, width: number, height: number): boolean;
/**
* Configures the URL for loading the WASM module.
* Call this before creating any player instances or calling `preload()` to load the WASM
* from a custom CDN or local path.
*
* Setting an explicit URL also disables the built-in jsdelivr/unpkg fallback: a failure
* to load from your URL surfaces as an error instead of falling through to a CDN.
* A load that is already in flight when this is called keeps the URLs it started with.
* @param url - URL pointing to the dotlottie WASM file
*/
static setWasmUrl(url: string): void;
/**
* Starts fetching and compiling the WASM module before any player is constructed.
* Call this at app or route load to take the WASM download off the first animation's critical path.
*/
static preload(): Promise<void>;
/**
* @experimental
* Register a custom font for use in animations
* @param fontName - The name of the font to register
* @param fontSource - Either a URL string to fetch the font, or ArrayBuffer/Uint8Array of font data
* @returns Promise<boolean> - true if registration succeeded, false otherwise
*/
static registerFont(fontName: string, fontSource: string | ArrayBuffer | Uint8Array): Promise<boolean>;
/**
* Gets the original dimensions of the animation as defined in the source file.
* Returns width and height in pixels representing the animation's intrinsic size.
* @returns Object with width and height properties in pixels
*/
animationSize(): {
height: number;
width: number;
};
/**
* @experimental
* Loads a state machine by its ID from the dotLottie manifest.
* State machines enable interactive, event-driven animation behaviors.
* @param stateMachineId - The ID of the state machine to load (must exist in manifest)
* @returns True if the state machine was loaded successfully, false otherwise
*/
stateMachineLoad(stateMachineId: string): boolean;
/**
* @experimental
* Load a state machine from data string
* @param stateMachineData - The state machine data as a string
* @returns true if the state machine was loaded successfully
*/
stateMachineLoadData(stateMachineData: string): boolean;
/**
* @experimental
* Set the state machine config
* @param config - The state machine config
*/
stateMachineSetConfig(config: StateMachineConfig | null): void;
/**
* @experimental
* Start the state machine
* @returns true if the state machine was started successfully
*/
stateMachineStart(): boolean;
/**
* @experimental
* Stop the state machine
* @returns true if the state machine was stopped successfully
*/
stateMachineStop(): boolean;
/**
* @experimental
* Get the current status of the state machine
* @returns The current status of the state machine as a string
*/
stateMachineGetStatus(): string;
/**
* @experimental
* Get the current state of the state machine
* @returns The current state of the state machine as a string
*/
stateMachineGetCurrentState(): string;
/**
* @experimental
* Get the active state machine ID
* @returns The active state machine ID as a string
*/
stateMachineGetActiveId(): string;
/**
* @experimental
* Override the current state of the state machine
* @param state - The state to override to
* @param immediate - Whether to immediately transition to the state
* @returns true if the state override was successful
*/
stateMachineOverrideState(state: string, immediate?: boolean): boolean;
/**
* @experimental
* Set the seed used by the state machine's random number generator
* @param seed - The seed value to use
* @returns true if the seed was set successfully
*/
stateMachineSetSeed(seed: number): boolean;
/**
* @experimental
* Get a specific state machine by ID
* @param stateMachineId - The ID of the state machine to get
* @returns The state machine data as a string
*/
stateMachineGet(stateMachineId: string): string;
/**
* @experimental
* Get the list of state machine listeners
* @returns Array of listener names
*/
stateMachineGetListeners(): string[];
/**
* @experimental
* Set a boolean input value for the state machine
* @param name - The name of the boolean input
* @param value - The boolean value to set
*/
stateMachineSetBooleanInput(name: string, value: boolean): boolean;
/**
* @experimental
* Set a numeric input value for the state machine
* @param name - The name of the numeric input
* @param value - The numeric value to set
*/
stateMachineSetNumericInput(name: string, value: number): boolean;
/**
* @experimental
* Set a string input value for the state machine
* @param name - The name of the string input
* @param value - The string value to set
*/
stateMachineSetStringInput(name: string, value: string): boolean;
/**
* @experimental
* Get a boolean input value from the state machine
* @param name - The name of the boolean input
* @returns The boolean value or undefined if not found
*/
stateMachineGetBooleanInput(name: string): boolean | undefined;
/**
* @experimental
* Get a numeric input value from the state machine
* @param name - The name of the numeric input
* @returns The numeric value or undefined if not found
*/
stateMachineGetNumericInput(name: string): number | undefined;
/**
* @experimental
* Get a string input value from the state machine
* @param name - The name of the string input
* @returns The string value or undefined if not found
*/
stateMachineGetStringInput(name: string): string | undefined;
/**
* @experimental
* Get all the inputs of the current state machine.
* @returns An array of input keys followed by its type at n+1.
*/
stateMachineGetInputs(): string[];
/**
* @experimental
* Fire an event in the state machine
* @param name - The name of the event to fire
*/
stateMachineFireEvent(name: string): void;
/**
* @experimental
* Post a click event to the state machine
* @param x - The x coordinate of the click
* @param y - The y coordinate of the click
*/
stateMachinePostClickEvent(x: number, y: number): void;
/**
* @experimental
* Post a pointer up event to the state machine
* @param x - The x coordinate of the pointer
* @param y - The y coordinate of the pointer
*/
stateMachinePostPointerUpEvent(x: number, y: number): void;
/**
* @experimental
* Post a pointer down event to the state machine
* @param x - The x coordinate of the pointer
* @param y - The y coordinate of the pointer
*/
stateMachinePostPointerDownEvent(x: number, y: number): void;
/**
* @experimental
* Post a pointer move event to the state machine
* @param x - The x coordinate of the pointer
* @param y - The y coordinate of the pointer
*/
stateMachinePostPointerMoveEvent(x: number, y: number): void;
/**
* @experimental
* Post a pointer enter event to the state machine
* @param x - The x coordinate of the pointer
* @param y - The y coordinate of the pointer
*/
stateMachinePostPointerEnterEvent(x: number, y: number): void;
/**
* @experimental
* Post a pointer exit event to the state machine
* @param x - The x coordinate of the pointer
* @param y - The y coordinate of the pointer
*/
stateMachinePostPointerExitEvent(x: number, y: number): void;
private _onClick;
private _onPointerUp;
private _onPointerDown;
private _onPointerMove;
private _onPointerEnter;
private _onPointerLeave;
private _setupStateMachineListeners;
private _cleanupStateMachineListeners;
}
//#endregion
//#region src/worker/dotlottie.d.ts
interface DotLottieInstanceState {
activeAnimationId: string | undefined;
activeThemeId: string | undefined;
autoplay: boolean;
backgroundColor: string;
currentFrame: number;
duration: number;
isFrozen: boolean;
isLoaded: boolean;
isPaused: boolean;
isPlaying: boolean;
isReady: boolean;
isStopped: boolean;
layout: Layout | undefined;
loop: boolean;
loopCount: number;
manifest: Manifest | null;
marker: string | undefined;
markers: Marker[];
mode: Mode;
renderConfig: RenderConfig;
segment: [number, number] | undefined;
speed: number;
totalFrames: number;
useFrameInterpolation: boolean;
volume: number;
}
/**
* Worker-based DotLottie player that offloads animation processing to a Web Worker thread.
* Use this for better performance when rendering multiple animations or to keep the main thread responsive.
* All methods are async (return Promises) due to worker communication. Requires HTMLCanvasElement or OffscreenCanvas.
*/
declare class DotLottieWorker {
private readonly _eventManager;
private _id;
private readonly _workerId;
private readonly _worker;
private _canvas;
private _dotLottieInstanceState;
private _created;
private _retired;
private _boundOnClick;
private _boundOnPointerUp;
private _boundOnPointerDown;
private _boundOnPointerMove;
private _boundOnPointerEnter;
private _boundOnPointerLeave;
private _pendingConfig;
/**
* Creates a worker-based DotLottie player instance that runs in a separate thread.
* Use workerId to share a worker across multiple animations for better resource management.
* @param config - Configuration with optional workerId to share worker threads
* @throws Error if canvas is not HTMLCanvasElement or OffscreenCanvas
*/
constructor(config: Config & {
workerId?: string;
});
private _handleWorkerEvent;
private _create;
private _adopt;
private _retire;
get loopCount(): number;
get isLoaded(): boolean;
get isPlaying(): boolean;
get isPaused(): boolean;
get isStopped(): boolean;
get currentFrame(): number;
get isFrozen(): boolean;
get totalFrames(): number;
get segment(): [number, number] | undefined;
get speed(): number;
get volume(): number;
get duration(): number;
get isReady(): boolean;
get mode(): Mode;
get canvas(): HTMLCanvasElement | OffscreenCanvas | null;
/**
* Sets the canvas element for rendering in the worker thread.
* Cannot change canvas after worker instance is created with a different canvas.
* @param canvas - HTMLCanvasElement or OffscreenCanvas to render to
* @returns Promise that resolves when canvas has been set
* @throws Error if canvas is not HTMLCanvasElement or OffscreenCanvas
* @throws Error if trying to change canvas after instance is already created
*/
setCanvas(canvas: HTMLCanvasElement | OffscreenCanvas): Promise<void>;
get autoplay(): boolean;
get backgroundColor(): string;
get loop(): boolean;
get useFrameInterpolation(): boolean;
get renderConfig(): RenderConfig;
get manifest(): Manifest | null;
get activeAnimationId(): string | undefined;
get marker(): string | undefined;
get activeThemeId(): string | undefined;
get layout(): Layout | undefined;
/**
* Starts or resumes animation playback in the worker thread.
* Updates the internal playback state (e.g., isPlaying) to reflect that playback has started.
* @returns Promise that resolves when playback has started and state has been updated
*/
play(): Promise<void>;
/**
* Pauses animation playback in the worker thread.
* Awaits worker response before resolving. Updates isPaused state to true.
* @returns Promise that resolves when playback has paused
*/
pause(): Promise<void>;
/**
* Stops animation playback and resets to start frame in the worker thread.
* Awaits worker response before resolving. Updates isStopped state to true.
* @returns Promise that resolves when playback has stopped
*/
stop(): Promise<void>;
/**
* Changes the animation playback speed in the worker thread.
* Awaits worker response before resolving.
* @param speed - Playback speed multiplier (e.g., 2 for 2x speed, 0.5 for half speed)
* @returns Promise that resolves when speed has been updated
*/
setSpeed(speed: number): Promise<void>;
/**
* Sets the audio volume in the worker thread. Kept across loads.
* @param volume - From 0 (muted) to 1 (full); values outside are clamped
* @returns Promise that resolves when the volume has been updated
*/
setVolume(volume: number): Promise<void>;
setMode(mode: Mode): Promise<void>;
setFrame(frame: number): Promise<void>;
setSegment(start: number, end: number): Promise<void>;
resetSegment(): Promise<void>;
setRenderConfig(renderConfig: RenderConfig): Promise<void>;
setUseFrameInterpolation(useFrameInterpolation: boolean): Promise<void>;
setTheme(themeId: string): Promise<boolean>;
/**
* Dynamically loads a new animation in the worker thread, replacing the current one.
* Awaits worker response before resolving. Stops current playback and cleans up resources.
* @param config - Configuration for the new animation (all Config properties except canvas)
* @returns Promise that resolves when animation has been loaded
*/
load(config: Omit<Config, 'canvas'>): Promise<void>;
setLoop(loop: boolean): Promise<void>;
/**
* Sets the number of additional times to replay the animation after the first play in the worker thread.
* Requires loop to be true. A value of 0 means infinite replays; a positive value n means
* the animation plays a total of n + 1 times (initial play + n replays).
* @param loopCount - Number of additional replays (0 = infinite, 1 = plays twice, 2 = plays three times, etc.)
* @returns Promise that resolves when loopCount has been updated
*/
setLoopCount(loopCount: number): Promise<void>;
/**
* Recalculates and updates canvas dimensions in the worker thread.
* Awaits worker response before resolving. Call when canvas container size changes.
* @returns Promise that resolves when resize has completed
*/
resize(): Promise<void>;
/**
* Cleans up and destroys the player instance in the worker thread, releasing resources.
* The facade becomes inert immediately; the worker-side teardown is deferred one
* macrotask so an immediate re-create on the same canvas (React StrictMode remount)
* can adopt the worker-side instance instead of re-transferring the canvas.
* @returns Promise that resolves when the facade has been made inert
*/
destroy(): Promise<void>;
private _finalizeDestroy;
freeze(): Promise<void>;
unfreeze(): Promise<void>;
setBackgroundColor(backgroundColor: string): Promise<void>;
loadAnimation(animationId: string): Promise<void>;
setLayout(layout: Layout): Promise<void>;
setSlots(slots: Record<string, unknown>): Promise<void>;
getSlotIds(): Promise<string[]>;
getSlotType(slotId: string): Promise<SlotType | undefined>;
getSlot(slotId: string): Promise<unknown>;
getSlots(): Promise<Record<string, unknown>>;
setColorSlot(slotId: string, value: ColorSlotValue): Promise<boolean>;
setScalarSlot(slotId: string, value: ScalarSlotValue): Promise<boolean>;
setVectorSlot(slotId: string, value: VectorSlotValue): Promise<boolean>;
setGradientSlot(slotId: string, value: GradientSlotValue, colorStopCount: number): Promise<boolean>;
setTextSlot(slotId: string, value: TextSlotValue): Promise<boolean>;
/**
* Set an image slot to a custom source.
*
* `http(s)://` URLs are fetched on the main thread and inlined as a `data:` URI before being
* sent to the worker, since the WASM renderer can only decode embedded images. `data:` URIs
* and package-relative file names are passed through unchanged.
* @param slotId - The image slot ID to set
* @param src - The image source: a `data:` URI, an `http(s)://` URL, or a package `i/` file name
* @returns true if successful
*/
setImageSlot(slotId: string, src: string): Promise<boolean>;
resetSlot(slotId: string): Promise<boolean>;
clearSlot(slotId: string): Promise<boolean>;
resetSlots(): Promise<boolean>;
clearSlots(): Promise<boolean>;
private _updateDotLottieInstanceState;
markers(): Marker[];
setMarker(marker: string): Promise<void>;
setThemeData(themeData: string): Promise<boolean>;
setViewport(x: number, y: number, width: number, height: number): Promise<boolean>;
animationSize(): Promise<{
height: number;
width: number;
}>;
setTransform(transform: Transform): Promise<boolean>;
getTransform(): Promise<Transform | undefined>;
private _sendMessage;
addEventListener<T extends EventType>(type: T, listener: EventListener<T>): void;
removeEventListener<T extends EventType>(type: T, listener?: EventListener<T>): void;
/**
* Configures the URL the worker loads the WASM module from.
* Call this before constructing any `DotLottieWorker` instance.
*
* An explicit URL disables the built-in jsdelivr/unpkg fallback, so a failure to load
* from it surfaces as a `loadError`. Relative URLs are resolved against the page.
* @param url - URL pointing to the dotlottie WASM file
*/
static setWasmUrl(url: string): void;
/**
* Point the worker to a self-hosted copy of `dotlottie.worker.js` so the
* library creates `new Worker(url)` instead of a `blob:` URL.
*
* This is required when the page's Content-Security-Policy does not allow
* `worker-src: blob:`. Call this before creating any `DotLottieWorker`
* instances — workers already running are unaffected.
*
* The file is shipped as `@lottiefiles/dotlottie-web/dotlottie.worker.js`
* and must be served from the same origin as the page. A URL-hosted worker
* inherits the page's CSP, so pair this with `setWasmUrl()` unless
* `connect-src` allows the jsdelivr/unpkg CDNs.
*
* @param url - URL pointing to the self-hosted worker script
*/
static setWorkerUrl(url: string): void;
/**
* @experimental
*
* Register a custom font for use in animations in worker contexts
* @param fontName - The name of the font to register
* @param fontSource - Either a URL string to fetch the font, or ArrayBuffer/Uint8Array of font data
* @returns Promise<boolean> - true if registration message was sent successfully
*/
static registerFont(fontName: string, fontSource: string | ArrayBuffer | Uint8Array): Promise<boolean>;
/**
* @experimental
* Load a state machine by ID
* @param stateMachineId - The ID of the state machine to load
* @returns true if the state machine was loaded successfully
*/
stateMachineLoad(stateMachineId: string): Promise<boolean>;
/**
* @experimental
* Load a state machine from data string
* @param stateMachineData - The state machine data as a string
* @returns true if the state machine was loaded successfully
*/
stateMachineLoadData(stateMachineData: string): Promise<boolean>;
/**
* @experimental
* Start the state machine
* @returns true if the state machine was started successfully
*/
stateMachineStart(): Promise<boolean>;
/**
* @experimental
* Stop the state machine
* @returns true if the state machine was stopped successfully
*/
stateMachineStop(): Promise<boolean>;
/**
* @experimental
* Set a numeric input value for the state machine
* @param name - The name of the numeric input
* @param value - The numeric value to set
* @returns true if the input was set successfully
*/
stateMachineSetNumericInput(name: string, value: number): Promise<boolean>;
/**
* @experimental
* Set a boolean input value for the state machine
* @param name - The name of the boolean input
* @param value - The boolean value to set
* @returns true if the input was set successfully
*/
stateMachineSetBooleanInput(name: string, value: boolean): Promise<boolean>;
/**
* @experimental
* Set the state machine config
* @param config - The state machine config
*/
stateMachineSetConfig(config: StateMachineConfig | null): Promise<void>;
/**
* @experimental
* Set a string input value for the state machine
* @param name - The name of the string input
* @param value - The string value to set
* @returns true if the input was set successfully
*/
stateMachineSetStringInput(name: string, value: string): Promise<boolean>;
/**
* @experimental
* Get a numeric input value from the state machine
* @param name - The name of the numeric input
* @returns The numeric value or undefined if not found
*/
stateMachineGetNumericInput(name: string): Promise<number | undefined>;
/**
* @experimental
* Get a boolean input value from the state machine
* @param name - The name of the boolean input
* @returns The boolean value or undefined if not found
*/
stateMachineGetBooleanInput(name: string): Promise<boolean | undefined>;
/**
* @experimental
* Get a string input value from the state machine
* @param name - The name of the string input
* @returns The string value or undefined if not found
*/
stateMachineGetStringInput(name: string): Promise<string | undefined>;
/**
* @experimental
* Get all inputs
* @returns All input keys, followed by their type
*/
stateMachineGetInputs(): Promise<string[] | undefined>;
/**
* @experimental
* Fire an event in the state machine
* @param name - The name of the event to fire
*/
stateMachineFireEvent(name: string): Promise<void>;
/**
* @experimental
* Get the current status of the state machine
* @returns The current status of the state machine as a string
*/
stateMachineGetStatus(): Promise<string>;
/**
* @experimental
* Get the current state of the state machine
* @returns The current state of the state machine as a string
*/
stateMachineGetCurrentState(): Promise<string>;
/**
* @experimental
* Get the active state machine ID
* @returns The active state machine ID as a string
*/
stateMachineGetActiveId(): Promise<string>;
/**
* @experimental
* Override the current state of the state machine
* @param state - The state to override to
* @param immediate - Whether to immediately transition to the state
* @returns true if the state override was successful
*/
stateMachineOverrideState(state: string, immediate?: boolean): Promise<boolean>;
/**
* @experimental
* Set the seed used by the state machine's random number generator
* @param seed - The seed value to use
* @returns true if the seed was set successfully
*/
stateMachineSetSeed(seed: number): Promise<boolean>;
/**
* @experimental
* Get a specific state machine by ID
* @param stateMachineId - The ID of the state machine to get
* @returns The state machine data as a string
*/
stateMachineGet(stateMachineId: string): Promise<string>;
/**
* @experimental
* Get the list of state machine listeners
* @returns Array of listener names
*/
stateMachineGetListeners(): Promise<string[]>;
/**
* @experimental
* Post a click event to the state machine
* @param x - The x coordinate of the click
* @param y - The y coordinate of the click
* @returns The event result or undefined
*/
stateMachinePostClickEvent(x: number, y: number): Promise<void>;
/**
* @experimental
* Post a pointer up event to the state machine
* @param x - The x coordinate of the pointer
* @param y - The y coordinate of the pointer
* @returns The event result or undefined
*/
stateMachinePostPointerUpEvent(x: number, y: number): Promise<void>;
/**
* @experimental
* Post a pointer down event to the state machine
* @param x - The x coordinate of the pointer
* @param y - The y coordinate of the pointer
* @returns The event result or undefined
*/
stateMachinePostPointerDownEvent(x: number, y: number): Promise<void>;
/**
* @experimental
* Post a pointer move event to the state machine
* @param x - The x coordinate of the pointer
* @param y - The y coordinate of the pointer
* @returns The event result or undefined
*/
stateMachinePostPointerMoveEvent(x: number, y: number): Promise<void>;
/**
* @experimental
* Post a pointer enter event to the state machine
* @param x - The x coordinate of the pointer
* @param y - The y coordinate of the pointer
* @returns The event result or undefined
*/
stateMachinePostPointerEnterEvent(x: number, y: number): Promise<void>;
/**
* @experimental
* Post a pointer exit event to the state machine
* @param x - The x coordinate of the pointer
* @param y - The y coordinate of the pointer
* @returns The event result or undefined
*/
stateMachinePostPointerExitEvent(x: number, y: number): Promise<void>;
private _onClick;
private _onPointerUp;
private _onPointerDown;
private _onPointerMove;
private _onPointerEnter;
private _onPointerLeave;
private _setupStateMachineListeners;
private _cleanupStateMachineListeners;
}
//#endregion
export { AssetResolver, BaseEvent, BezierHandle, Color, ColorSlotValue, CompleteEvent, Config, Data, DestroyEvent, DotLottie, DotLottieInstanceState, DotLottieWorker, Event, EventListener, EventManager, EventType, Fit, FrameEvent, FreezeEvent, Gradient, GradientSlotValue, Keyframe, Layout, LoadErrorEvent, LoadEvent, LoopEvent, Manifest, Marker, Mode, PauseEvent, PlayEvent, ReadyEvent, RenderConfig, RenderErrorEvent, RenderEvent, RenderSurface, ScalarSlotValue, SlotType, StateMachineBooleanInputValueChangeEvent, StateMachineConfig, StateMachineCustomEvent, StateMachineErrorEvent, StateMachineInputFiredEvent, StateMachineInternalMessage, StateMachineNumericInputValueChangeEvent, StateMachineStartEvent, StateMachineStateEnteredEvent, StateMachineStateExitEvent, StateMachineStopEvent, StateMachineStringInputValueChangeEvent, StateMachineTransitionEvent, StopEvent, TextDocument, TextSlotValue, Theme, ThemeBaseKeyframe, ThemeBaseRule, ThemeColorKeyframe, ThemeColorRule, ThemeGradientKeyframe, ThemeGradientRule, ThemeGradientStop, ThemeImageRule, ThemeImageValue, ThemePositionKeyframe, ThemePositionRule, ThemeRule, ThemeScalarKeyframe, ThemeScalarRule, ThemeTextCaps, ThemeTextDocument, ThemeTextJustify, ThemeTextKeyframe, ThemeTextRule, ThemeVectorKeyframe, ThemeVectorRule, Transform, UnfreezeEvent, Vector, VectorSlotValue, WebGLConfig, WebGPUConfig };
//# sourceMappingURL=index.d.cts.map