dotLottie Web Player API Reference

Complete reference for the dotLottie web player - constructor options, properties, methods, events, layout and render configuration, and types.

Configuration

The DotLottie constructor accepts a configuration object with the following properties:

PropertyTypeRequiredDefaultDescription
canvasHTMLCanvasElement✔️undefinedCanvas element for animation rendering
srcstringundefinedURL to the animation data (.json or .lottie)
datastring | ArrayBuffer | Record<string, unknown>undefinedAnimation data as a Lottie JSON string, an ArrayBuffer for .lottie files, or a pre-parsed JSON object
autoplaybooleanfalseAuto-starts the animation on load
loopbooleanfalseDetermines if the animation should loop
loopCountnumber0Number of additional loop repetitions (0 = infinite when loop is true)
speednumber1Animation playback speed. 1 is regular speed
modestring"forward"Animation play mode. Accepts "forward", "reverse", "bounce", "reverse-bounce"
segment[number, number][0, totalFrames - 1]Animation segment. Accepts an array of two numbers: start frame and end frame
markerstringundefinedThe lottie named marker to play
animationIdstringundefinedID of the animation to load from a multi-animation dotLottie file
themeIdstringundefinedThe ID of the dotLottie theme to initially use
backgroundColorstringundefinedBackground color of the canvas. Accepts 6-digit or 8-digit hex color string (e.g., "#000000", "#000000FF")
layoutLayoutundefinedThe animation layout configuration
renderConfigRenderConfig{}Configuration for rendering the animation (see Render Configuration)
useFrameInterpolationbooleantrueDetermines if the animation should update on subframes. When false, the animation updates only on whole frames, which reduces rendering work.
stateMachineIdstringundefinedID of the state machine to load on animation load
stateMachineConfigStateMachineConfigundefinedSecurity configuration for the state machine (see StateMachineConfig)
assetResolverAssetResolverundefinedA synchronous callback that supplies bytes for assets the animation references but does not embed (see AssetResolver). Not supported by DotLottieWorker.

Properties

DotLottie instances expose the following read-only properties:

PropertyTypeDescription
currentFramenumberThe animation's currently displayed frame number
durationnumberThe animation's total playback time in milliseconds
segmentDurationnumberDuration of the current segment in milliseconds
totalFramesnumberTotal count of individual frames within the animation
loopbooleanWhether the animation is set to play in a continuous loop
speednumberPlayback speed factor (e.g., 2 means double speed)
loopCountnumberNumber of times the animation has completed its loop
modestringCurrent playback mode
isPausedbooleanWhether the animation is paused
isStoppedbooleanWhether the animation is stopped
isPlayingbooleanWhether the animation is playing
isLoadedbooleanWhether the animation is loaded
isReadybooleanWhether the WASM renderer module is initialized
isFrozenbooleanWhether the animation loop is frozen
isStateMachineRunningbooleanWhether a state machine is currently running
segment[number, number]Current frame range being played
backgroundColorstringCurrent background color of the canvas
autoplaybooleanWhether the animation is set to auto-play
useFrameInterpolationbooleanWhether the animation updates on subframes
renderConfigRenderConfigCurrent rendering configuration
manifestManifest | nullThe manifest of the loaded dotLottie file
markerstring | undefinedThe current lottie named marker
layoutLayout | undefinedThe current animation layout configuration
activeThemeIdstringThe ID of the currently active theme
activeAnimationIdstringThe ID of the currently active animation
canvasHTMLCanvasElement | OffscreenCanvas | RenderSurface | nullThe canvas element used for rendering
bufferUint8Array | nullThe raw pixel buffer for the current frame

Methods

Playback Control

MethodDescription
play()Begins playback from the current animation position
pause()Pauses the animation without resetting its position
stop()Halts playback and returns the animation to its initial frame
setSpeed(speed: number)Sets the playback speed with the given multiplier
setLoop(loop: boolean)Configures whether the animation should loop continuously
setLoopCount(loopCount: number)Sets the number of loop repetitions
setFrame(frame: number)Directly navigates the animation to a specified frame
setMode(mode: string)Sets the animation play mode ("forward", "reverse", "bounce", "reverse-bounce")
setSegment(startFrame: number, endFrame: number)Sets the start and end frame of the animation
setMarker(marker: string)Sets the lottie named marker to play
freeze()Freezes the animation by stopping the animation loop
unfreeze()Unfreezes the animation by resuming the animation loop
setUseFrameInterpolation(useFrameInterpolation: boolean)Sets whether the animation should update on subframes. When false, rendering work is reduced.
tween(frame: number, duration: number)Smoothly tweens the animation from the current frame to the specified frame over the given duration (ms)
tweenToMarker(marker: string, duration: number)Smoothly tweens the animation to the start of the named marker over the given duration (ms)
markers()Returns all markers defined in the animation as an array of Marker objects

Animation Loading & Themes

MethodDescription
load(config: Config)Loads a new configuration or animation
loadAnimation(animationId: string)Loads a specific animation from a multi-animation .lottie file by ID
setTheme(themeId: string)Loads a theme by ID from the .lottie file
setThemeData(themeData: string)Loads a theme from the provided theme data string
resetTheme()Resets to the default theme

Slot System (Dynamic Properties)

Slots allow runtime modification of animation properties such as colors, text, and gradients.

MethodDescription
getSlotIds()Returns an array of all available slot IDs
getSlotType(slotId: string)Returns the type of the slot ("color", "scalar", "vector", "gradient", "text", "image")
getSlot(slotId: string)Returns the current value of a slot
getSlots()Returns all slot values as a record
setSlots(slots: Record<string, unknown>)Sets multiple slot values at once
setColorSlot(slotId: string, value: ColorSlotValue)Sets a color slot value (static or animated)
setScalarSlot(slotId: string, value: ScalarSlotValue)Sets a scalar (numeric) slot value
setVectorSlot(slotId: string, value: VectorSlotValue)Sets a vector slot value
setGradientSlot(slotId: string, value: GradientSlotValue, colorStopCount: number)Sets a gradient slot value
setTextSlot(slotId: string, value: TextSlotValue)Sets a text slot value
resetSlot(slotId: string)Resets a slot to its default value
clearSlot(slotId: string)Clears a slot value
resetSlots()Resets all slots to their default values
clearSlots()Clears all slot values

Methods that modify state (setTheme, resetTheme, setThemeData, setTransform, setViewport, tween, tweenToMarker, stateMachineLoad, stateMachineStart, stateMachineOverrideState, and all slot setters like setColorSlot, resetSlot, clearSlot, etc.) return booleantrue on success, false on failure.

Rendering & Layout

MethodDescription
setBackgroundColor(color: string)Sets the background color of the canvas
setLayout(layout: Layout)Sets the animation layout configuration
setRenderConfig(renderConfig: RenderConfig)Sets the render configuration
setViewport(x: number, y: number, width: number, height: number)Sets a custom viewport within the canvas
setTransform(transform: Transform)Applies a 3×3 affine transformation matrix to the animation
getTransform()Returns the current transformation matrix
setCanvas(canvas: HTMLCanvasElement | OffscreenCanvas)Reassigns the player to a different canvas element
resize()Adjusts the canvas size to match its bounding box dimensions
animationSize()Returns the intrinsic { width, height } of the animation
getLayerBoundingBox(layerName: string)Returns the bounding box [x, y, width, height] of a named layer

State Machine

See the State Machines guide for full documentation. Quick reference:

MethodDescription
stateMachineLoad(stateMachineId: string)Loads a state machine by ID
stateMachineLoadData(stateMachineData: string)Loads a state machine from a JSON string
stateMachineSetConfig(config: StateMachineConfig | null)Configures security settings for the state machine
stateMachineStart()Starts the loaded state machine
stateMachineStop()Stops the state machine
stateMachineGetStatus()Returns the state machine status string
stateMachineGetCurrentState()Returns the name of the active state
stateMachineGetActiveId()Returns the ID of the active state machine
stateMachineGet(stateMachineId: string)Returns the state machine definition JSON
stateMachineGetListeners()Returns names of all active listeners
stateMachineOverrideState(state: string, immediate: boolean)Overrides the current state
stateMachineFireEvent(name: string)Fires a named custom event
stateMachinePostClickEvent(x: number, y: number)Posts a click event at canvas coordinates
stateMachinePostPointerUpEvent(x: number, y: number)Posts a pointer-up event at canvas coordinates
stateMachinePostPointerDownEvent(x: number, y: number)Posts a pointer-down event at canvas coordinates
stateMachinePostPointerMoveEvent(x: number, y: number)Posts a pointer-move event at canvas coordinates
stateMachinePostPointerEnterEvent(x: number, y: number)Posts a pointer-enter event at canvas coordinates
stateMachinePostPointerExitEvent(x: number, y: number)Posts a pointer-exit event at canvas coordinates
stateMachineSetBooleanInput(name: string, value: boolean)Sets a boolean input
stateMachineSetNumericInput(name: string, value: number)Sets a numeric input
stateMachineSetStringInput(name: string, value: string)Sets a string input
stateMachineGetBooleanInput(name: string)Gets a boolean input value
stateMachineGetNumericInput(name: string)Gets a numeric input value
stateMachineGetStringInput(name: string)Gets a string input value
stateMachineGetInputs()Returns the names of all defined inputs

Event Listeners

MethodDescription
addEventListener(event: string, listener: Function)Registers a function to respond to a specific animation event
removeEventListener(event: string, listener?: Function)Removes a previously registered event listener

Lifecycle

MethodDescription
destroy()Destroys the renderer instance and unregisters all event listeners. Instances that are not destroyed retain their allocated resources.

Static Methods

MethodDescription
DotLottie.setWasmUrl(url: string)Sets the URL to the renderer.wasm binary
DotLottie.preload()Starts fetching and compiling the WASM module before any player is constructed. Returns a Promise<void> that resolves when the WASM is ready.
DotLottie.registerFont(fontName: string, fontSource: string | ArrayBuffer | Uint8Array)Registers a custom font for use in text slots
DotLottie.transformThemeToLottieSlots(theme: string, slots: string)Utility to transform theme data to Lottie slot format

DotLottie.preload() starts the WASM download (~500 KB compressed) before any player is constructed. A player constructed afterwards uses the in-progress download instead of starting its own:

import { DotLottie } from "@lottiefiles/dotlottie-web";

// At app or route load, before any player is constructed:
DotLottie.preload();

When a custom WASM binary is used, setWasmUrl() must be called before preload():

DotLottie.setWasmUrl("/assets/dotlottie-player.wasm");
DotLottie.preload();

GPU-Accelerated Rendering

The WebGL2 and WebGPU backends live on package subpaths, and each one exports its player class as DotLottie. Alias it on import to name the backend and to avoid a collision when a file uses more than one. For guidance on choosing a backend, detecting support, and falling back, see Render on the GPU with WebGL or WebGPU.

Both classes narrow the constructor config: canvas is required and must be an HTMLCanvasElement, so OffscreenCanvas and RenderSurface are not accepted. Neither backend has a Web Worker equivalent — DotLottieWorker is exported only from the package root and always renders on the CPU.

WebGL renderer

Import from @lottiefiles/dotlottie-web/webgl for WebGL2-accelerated rendering, configured with a WebGLConfig:

import { DotLottie as DotLottieWebGL } from "@lottiefiles/dotlottie-web/webgl";

const animation = new DotLottieWebGL({
  canvas: document.getElementById("my-canvas") as HTMLCanvasElement,
  src: "animation.lottie",
  autoplay: true,
});
Static MethodDescription
DotLottieWebGL.setWasmUrl(url: string)Sets the URL to the WebGL renderer WASM binary
DotLottieWebGL.preload()Starts fetching and compiling the WebGL WASM module before any player is constructed. Returns a Promise<void> that resolves when ready.

Both static methods apply only to the WebGL backend's own WASM loader; calling them on DotLottie has no effect here. The browser must support WebGL2. All instance methods, properties, and events from DotLottie are available.

WebGPU renderer

Import from @lottiefiles/dotlottie-web/webgpu for WebGPU-accelerated rendering, configured with a WebGPUConfig:

import { DotLottie as DotLottieWebGPU } from "@lottiefiles/dotlottie-web/webgpu";

const animation = new DotLottieWebGPU({
  canvas: document.getElementById("my-canvas") as HTMLCanvasElement,
  src: "animation.lottie",
  autoplay: true,
  device: gpuDevice, // optional: pass your own GPUDevice
});

The WebGPUConfig extends the standard Config with:

PropertyTypeRequiredDefaultDescription
deviceGPUDeviceNoundefinedAn existing WebGPU device. If omitted, one is requested automatically.

The instance also exposes the device it renders with:

PropertyTypeDescription
deviceGPUDevice | nullThe active WebGPU device. null before initialization completes and after destroy().
Static MethodDescription
DotLottieWebGPU.setWasmUrl(url: string)Sets the URL to the WebGPU renderer WASM binary
DotLottieWebGPU.preload()Starts fetching and compiling the WebGPU WASM module before any player is constructed. Returns a Promise<void> that resolves when ready.

When you omit device, the player requests an adapter and device during initialization and destroys that device in destroy(). A device you supply is left untouched.

:::warning WebGPU is an emerging API with limited browser support. Initialization failures on either GPU backend — a missing navigator.gpu or no available adapter for WebGPU, no WebGL2 context for WebGL — do not throw from the constructor; they surface as a loadError event. :::

Events

The following events can be listened to via addEventListener:

Animation Events

EventDescriptionEvent Parameter
readyWASM renderer is initialized{ type: 'ready' }
loadAnimation is loaded{ type: 'load' }
loadErrorError loading animation{ type: 'loadError', error: Error }
playAnimation starts playing{ type: 'play' }
pauseAnimation is paused{ type: 'pause' }
stopAnimation is stopped{ type: 'stop' }
loopAnimation completes a loop{ type: 'loop', loopCount: number }
completeAnimation completes{ type: 'complete' }
frameAnimation reaches new frame{ type: 'frame', currentFrame: number }
renderNew frame is rendered{ type: 'render', currentFrame: number }
freezeAnimation is frozen{ type: 'freeze' }
unfreezeAnimation is unfrozen{ type: 'unfreeze' }
destroyAnimation is destroyed{ type: 'destroy' }
renderErrorRendering error occurred{ type: 'renderError', error: Error }

State Machine Events

EventDescriptionEvent Parameter
stateMachineStartState machine started{ type: 'stateMachineStart' }
stateMachineStopState machine stopped{ type: 'stateMachineStop' }
stateMachineTransitionState transition occurred{ type: 'stateMachineTransition', fromState: string, toState: string }
stateMachineStateEnteredEntered a new state{ type: 'stateMachineStateEntered', state: string }
stateMachineStateExitExited a state{ type: 'stateMachineStateExit', state: string }
stateMachineCustomEventCustom event emitted by state machine{ type: 'stateMachineCustomEvent', eventName: string }
stateMachineErrorState machine error{ type: 'stateMachineError', error: string }
stateMachineBooleanInputValueChangeBoolean input value changed{ type, inputName: string, oldValue: boolean, newValue: boolean }
stateMachineNumericInputValueChangeNumeric input value changed{ type, inputName: string, oldValue: number, newValue: number }
stateMachineStringInputValueChangeString input value changed{ type, inputName: string, oldValue: string, newValue: string }
stateMachineInputFiredAn input fired{ type: 'stateMachineInputFired', inputName: string }
stateMachineInternalMessageInternal state machine message{ type: 'stateMachineInternalMessage', message: string }

Layout Configuration

The layout object accepts the following properties:

PropertyTypeRequiredDefaultDescription
fitstring"contain"The fit mode of the animation. Accepts "contain", "cover", "fill", "fit-width", "fit-height", "none"
align[number, number][0.5, 0.5]The alignment of the animation in the canvas. [0, 0] is top-left and [1, 1] is bottom-right

Render Configuration

The renderConfig object allows customization of rendering settings:

PropertyTypeRequiredDefaultDescription
devicePixelRationumberNowindow.devicePixelRatio * 0.75 if DPI > 1, else 1Controls the pixel ratio for rendering
freezeOnOffscreenbooleanNotrueFreezes animation when offscreen to conserve resources (improves performance when many animations are present but not visible)
autoResizebooleanNofalseAutomatically adjusts animation size when canvas element is resized
qualitynumberNoundefinedRendering quality level (0–100). Controls the resolution scale of the internal render surface. A value of 100 renders at full resolution. Lower values reduce the resolution proportionally, improving performance at the cost of visual fidelity.

StateMachineConfig

The stateMachineConfig object controls security settings for state machine execution:

PropertyTypeDescription
openUrlPolicyobjectControls URL-opening behavior triggered by state machines
openUrlPolicy.requireUserInteractionbooleanWhen true, URLs can only be opened in response to direct user interaction
openUrlPolicy.whiteliststring[]List of allowed URL prefixes that the state machine may open

Type Definitions

AssetResolver

AssetResolver is a synchronous callback used to supply bytes for assets that an animation references but does not embed — for example, images stored outside the .lottie container.

type AssetResolver = (src: string) => ArrayBuffer | Uint8Array | null | undefined;
ParameterTypeDescription
srcstringThe asset path as referenced by the animation, e.g. "/images/img_0.png"

The resolver is called synchronously while the animation loads, so the asset bytes must already be available in memory. Return null or undefined to leave an asset unresolved — unresolved images render as a gray placeholder.

import { DotLottie } from "@lottiefiles/dotlottie-web";

// Pre-load your assets into a Map (or any lookup you choose)
const assets = new Map<string, Uint8Array>();
assets.set("/images/logo.png", await fetchAsBytes("/images/logo.png"));

const dotLottie = new DotLottie({
  canvas: document.querySelector("#canvas") as HTMLCanvasElement,
  src: "animation.json",
  autoplay: true,
  assetResolver: (src) => assets.get(src) ?? null,
});

:::warning assetResolver is not supported by DotLottieWorker. Functions cannot be transferred across the worker boundary — if you pass assetResolver to DotLottieWorker, it will be silently dropped and a console warning will be logged. Use DotLottie instead when your animation references external assets. :::

If you call load() to reload the animation with a new configuration, pass assetResolver again in the new config — load() replaces the full configuration.

Slot Types

TypeDefinitionDescription
ColorSlotValueColor | Array<Keyframe<Color>>Static or animated color
ScalarSlotValuenumber | Array<Keyframe<number>>Static or animated scalar (number)
VectorSlotValueVector | Array<Keyframe<Vector>>Static or animated vector [x, y]
GradientSlotValueGradient | Array<Keyframe<Gradient>>Static or animated gradient with color stops
TextSlotValueTextDocumentStatic text with optional font, size, color
SlotType"color" | "gradient" | "image" | "text" | "scalar" | "vector"Possible slot types

Transform

A Transform is a 9-element array [a, b, c, d, e, f, g, h, i] representing a 3×3 affine transformation matrix applied to the entire animation on the canvas.

Marker

interface Marker {
  name: string;
  time: number;
  duration: number;
}

Data

The Data type represents animation data that can be passed to the data configuration option:

type Data = string | ArrayBuffer | Record<string, unknown>;
  • string — A Lottie JSON string

  • ArrayBuffer — A .lottie file binary

  • Record<string, unknown> — A pre-parsed Lottie JSON object

Manifest Object

The manifest property returns the parsed manifest.json object from the loaded .lottie file (or null if a .json file was loaded or loading failed). This object contains metadata about the animation(s), themes, and state machines within the dotLottie file.

Key properties:

  • manifest.animations: An array of objects, each describing an animation within the file (containing id, loop, speed, etc.).

  • manifest.themes: An array describing available themes.

  • manifest.stateMachines: An array describing available state machines.

  • manifest.version: The dotLottie format version string.

  • manifest.generator: The tool that generated the file.

The dotLottie Format Structure documentation describes the manifest structure and all its properties.

Last updated: August 13, 2026 at 9:17 AMEdit this page