Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@lottiefiles/dotlottie-web

Package Overview
Dependencies
Maintainers
4
Versions
74
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@lottiefiles/dotlottie-web

Lottie and DotLottie player for the web

  • 0.27.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
117K
increased by19.78%
Maintainers
4
Weekly downloads
 
Created
Source

@lottiefiles/dotlottie-web

npm npm bundle size npm NPM

Contents

Introduction

A JavaScript library for rendering lottie and dotLottie animations in the browser.

What is dotLottie?

dotLottie is an open-source file format that aggregates one or more Lottie files and their associated resources into a single file. They are ZIP archives compressed with the Deflate compression method and carry the file extension of ".lottie".

Learn more about dotLottie.

Prerequisites

Installation

npm install @lottiefiles/dotlottie-web

Usage

Via npm

After installation, you can import DotLottie in your JavaScript or TypeScript module:

<!-- Canvas element where the animation will be rendered -->
<canvas id="dotlottie-canvas" style="width: 300px; height:300px;"></canvas>
import { DotLottie } from '@lottiefiles/dotlottie-web';

const dotLottie = new DotLottie({
    autoplay: true,
    loop: true,
    canvas: document.querySelector('#dotlottie-canvas'),
    src: "https://lottie.host/4db68bbd-31f6-4cd8-84eb-189de081159a/IGmMCqhzpt.lottie", // or .json file
});

Via CDN

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />
    <title>@lottiefiles/dotlottie-web | basic example</title>
  </head>
  <body>
    <!-- Canvas element where the Lottie animation will be rendered -->
    <canvas id="canvas" width="300" height="300"></canvas>
    <script type="module">
      import { DotLottie } from "https://cdn.jsdelivr.net/npm/@lottiefiles/dotlottie-web/+esm";

      new DotLottie({
        autoplay: true,
        loop: true,
        canvas: document.getElementById("canvas"),
        src: "https://lottie.host/4db68bbd-31f6-4cd8-84eb-189de081159a/IGmMCqhzpt.lottie", // or .json file
      });
    </script>
  </body>
</html>

Live Examples

APIs

Config

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

Property nameTypeRequiredDefaultDescription
autoplaybooleanfalseAuto-starts the animation on load.
loopbooleanfalseDetermines if the animation should loop.
canvasHTMLCanvasElement | OffscreenCanvas✔️undefinedCanvas element for animation rendering.
srcstringundefinedURL to the animation data (.json or .lottie).
speednumber1Animation playback speed. 1 is regular speed.
datastring | ArrayBufferundefinedAnimation data provided either as a Lottie JSON string or as an ArrayBuffer for .lottie animations.
modestring"forward"Animation play mode. Accepts "forward", "reverse", "bounce", "reverse-bounce".
backgroundColorstringundefinedBackground color of the canvas. Accepts 6-digit or 8-digit hex color string (e.g., "#000000", "#000000FF"),
segment[number, number][0, totalFrames - 1]Animation segment. Accepts an array of two numbers, where the first number is the start frame and the second number is the end frame.
renderConfigRenderConfig{}Configuration for rendering the animation.
useFrameInterpolationbooleantrueDetermines if the animation should update on subframes. If set to false, the original AE frame rate will be maintained. If set to true, it will refresh at each requestAnimationFrame, including intermediate values. The default setting is true.
markerstringundefinedThe lottie named marker to play.
layoutLayoutundefinedThe animation layout configuration.
Layout

The layout object accepts the following properties:

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

The renderConfig object accepts the following properties:

Property nameTypeRequiredDefaultDescription
devicePixelRationumberwindow.devicePixelRatio | 1The device pixel ratio.

Properties

DotLottie instances expose the following properties:

PropertyTypeDescription
currentFramenumberRepresents the animation's currently displayed frame number.
durationnumberSpecifies the animation's total playback time in milliseconds.
totalFramesnumberDenotes the total count of individual frames within the animation.
loopbooleanIndicates if the animation is set to play in a continuous loop.
speednumberRepresents the playback speed factor; e.g., 2 would mean double speed.
loopCountnumberTracks how many times the animation has completed its loop.
directionstringReflects the current playback direction; e.g., 1 would mean forward, -1 would mean reverse.
modestringReflects the current playback mode.
isPausedbooleanReflects whether the animation is paused or not.
isStoppedbooleanReflects whether the animation is stopped or not.
isPlayingbooleanReflects whether the animation is playing or not.
segment[number, number]Reflects the frames range of the animations. where segment[0] is the start frame and segment[1] is the end frame.
backgroundColorstringGets the background color of the canvas.
autoplaybooleanIndicates if the animation is set to auto-play.
isFrozenbooleanReflects whether the animation loop is stopped or not.
isLoadedbooleanReflects whether the animation is loaded or not.
useFrameInterpolationbooleanReflects whether the animation should update on subframes.
renderConfigRenderConfigConfiguration for rendering the animation.
manifestManifest | nullThe manifest of the loaded dotLottie file.
markerstringThe lottie named marker to play.
layoutLayoutThe animation layout configuration.
activeThemeIdstringThe loaded theme id from the .lottie file.
activeAnimationIdstringThe loaded animation id from the .lottie file.
segmentDurationnumberThe duration of the current segment, if no segment is set, it will return the duration of the whole animation.
canvasHTMLCanvasElement | OffscreenCanvasThe canvas element for animation rendering.
Manifest

This object contains the manifest of the loaded dotLottie file. as described in the dotLottie structure.

Methods

DotLottie instances expose the following methods that can be used to control the animation:

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.
setFrame(frame: number)Directly navigates the animation to a specified frame.
addEventListener(event: string, listener: Function)Registers a function to respond to a specific animation event.
removeEventListener(event: string, listener?: Function)Removes a previously registered function from responding to a specific animation event.
destroy()Destroys the renderer instance and unregisters all event listeners. This method should be called when the canvas is removed from the DOM to prevent memory leaks.
load(config: Config)Loads a new configuration or a new animation.
setMode(mode: string)Sets the animation play mode.
setSegment(startFrame: number, endFrame: number)Sets the start and end frame of the animation.
freeze()Freezes the animation by stopping the animation loop.
unfreeze()Unfreezes the animation by resuming the animation loop.
setBackgroundColor(color: string)Sets the background color of the canvas.
resize()This method adjusts the canvas size to match its bounding box dimensions, considering the device's pixel ratio. This prevents the canvas from appearing blurry on high-resolution screens. Call this method when the window or the canvas element is resized.
setUseFrameInterpolation(useFrameInterpolation: boolean)Sets whether the animation should update on subframes.
setRenderConfig(renderConfig: RenderConfig)Sets the render configuration. check RenderConfig for more details.
loadAnimation(animationId: string)Loads a new animation from the .lottie file, using its ID as specified in the manifest.json file of the .lottie file.
setMarker(marker: string)Sets the lottie named marker to play.
setLayout(layout: Layout)Sets the animation layout configuration.
loadTheme(themeId: string)Loads a new theme from the .lottie file, using its ID as specified in the manifest.json file of the .lottie file.
loadThemeData(themeData: string)Loads a new theme from the provided theme data.
setViewport(x: number, y: number, width: number, height: number)Sets the viewport of the animation, where x and y are the top-left corner of the viewport, and width and height are the dimensions of the viewport, this will crop the animation to the specified viewport.
loadStateMachineData(stateMachineData: string)Loads the state machine data as a json string.
animationSize(): {width: number, height: number}Retrieves the original lottie animation size.
setStateMachineBooleanContext(name: string, value: boolean)Sets the state machine context with a boolean value.
setStateMachineStringContext(name: string, value: string)Sets the state machine context with a string value.
setStateMachineNumericContext(name: string, value: number)Sets the state machine context with a numeric value.

Static Methods

The DotLottie class exposes the following static methods:

MethodDescription
setWasmUrl(url: string)Sets the URL to the renderer.wasm binary.

Events

The DotLottie instance emits the following events that can be listened to via the addEventListener method:

EventDescriptionEvent Parameter (Type and Fields)
loadEmitted when the animation is loaded.LoadEvent { type: 'load' }
loadErrorEmitted when there's an error loading the animation.LoadErrorEvent { type: 'loadError', error: Error }
playEmitted when the animation starts playing.PlayEvent { type: 'play' }
pauseEmitted when the animation is paused.PauseEvent { type: 'pause' }
stopEmitted when the animation is stopped.StopEvent { type: 'stop' }
loopEmitted when the animation completes a loop.LoopEvent { type: 'loop', loopCount: number }
completeEmitted when the animation completes.CompleteEvent { type: 'complete' }
frameEmitted when the animation reaches a new frame.FrameEvent { type: 'frame', currentFrame: number }
destroyEmitted when the animation is destroyed.DestroyEvent { type: 'destroy' }
freezeEmitted when the animation is freezed and the animation loop stops.FreezeEvent { type: 'freeze' }
unfreezeEmitted when the animation is unfreezed and the animation loop resumes.UnfreezeEvent { type: 'unfreeze' }
renderEmitted when a new frame is rendered to the canvas.RenderEvent { type: 'render', currentFrame: number }

Development

Setup

pnpm install

Dev

pnpm dev

Build

pnpm build

Test

  pnpm test

Keywords

FAQs

Package last updated on 03 Jul 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc