Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
SVGAPlayer-Web-Lite
https://github.com/svga/svgaplayer-web-lite
Admin
这是一个 SVGA 在移动端 Web 上的播放器,它的目标是更轻量、更高效。
Tokens:
32,547
Snippets:
241
Trust Score:
8
License:
Apache-2.0
Update:
1 month ago
Context
Chat
Benchmark
85.67
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### start() Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/animator.md Starts the animation loop, setting isRunning to true, recording start time, resetting the current fraction, and invoking the onStart callback. ```APIDOC ## `start()` ### Description Starts the animation loop. Sets `isRunning = true`, records `startTime`, resets `currentFrication` to `0.0`, lazily creates a no-execution-delay Worker, invokes `onStart()`, and starts the first `doFrame()`. ### Method `start` ### Signature ts public start (): void ### Parameters None ### Returns `void` ### Behavior - Sets `isRunning = true` - Records `startTime` - Resets `currentFrication` to `0.0` - Lazily creates a Worker with script `'onmessage = function () {setTimeout(function() {postMessage(null)}, 1000 / 60)}'` - Invokes `onStart()` - Starts the first `doFrame()` ### Throws None ``` -------------------------------- ### start() Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/player.md Clears the container, starts the animation timeline (startAnimation), then fires onStart. Throws Error('videoEntity undefined') if no video is mounted. ```APIDOC ## start() ### Description Clears the container, starts the animation timeline (`startAnimation`), then fires `onStart`. ### Method `start()` ### Signature ```ts public start (): void ``` ### Throws - `Error('videoEntity undefined')` - No video mounted yet. ``` -------------------------------- ### start() method signature Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/player.md Signature for the start() method. Clears the container, starts the animation timeline, and fires onStart. Throws Error('videoEntity undefined') if no video is mounted. ```typescript public start (): void ``` -------------------------------- ### Basic Animator setup and start Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/animator.md Configures an Animator to animate from frame 0 to 59 over 1 second, looping forever, and logs each frame value via onUpdate. The fillRule is set to 0 to finish at the last frame when stopped by completion. ```javascript import { Animator } from 'svga/player/animator' // module path in src const animator = new Animator() animator.startValue = 0 animator.endValue = 59 // 60 frames total animator.duration = 1000 // 1 second animator.loop = Infinity // loop forever animator.fillRule = 0 // finish at the last frame when stopped by completion animator.onUpdate = value => { console.log('frame', value) } animator.start() ``` -------------------------------- ### Handling playback and configuration errors Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/player.md Illustrates how to catch synchronous errors when calling start() before mounting a video or providing invalid frame ranges to setConfig. ```js import { Parser, Player } from 'svga' const player = new Player(document.getElementById('canvas')) // Throws synchronously: Error('videoEntity undefined') try { player.start() } catch (error) { console.error('cannot start before mount:', error) } // Throws synchronously: Error('StartFrame should > EndFrame') try { player.setConfig({ startFrame: 20, endFrame: 10 }) } catch (error) { console.error('invalid frame range:', error) } const parser = new Parser() const video = await parser.load('https://example.com/anim.svga') await player.mount(video) player.start() ``` -------------------------------- ### Usage example - Utils.getVersion Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/utils.md Shows how to call Utils.getVersion on a fetched SVGA buffer. Logs 2 for files the parser can handle and 1 for legacy SVGA packages. No throws are defined in Utils itself. ```typescript import { Utils } from './utils' // module path in src const buffer = await fetch('https://example.com/x.svga').then(r => r.arrayBuffer()) const version = Utils.getVersion(buffer) console.log(version) // 2 for files this parser can handle, 1 for legacy SVGA packages ``` -------------------------------- ### DB constructor signature Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/db.md Shows the constructor signature with an optional configuration object. Defaults are name: 'SVGA.DB', version: 1.0, storeName: 'files'. The constructor starts opening the database asynchronously and throws synchronously if window.indexedDB is undefined. ```typescript constructor ({ name, version, storeName }: { name: string version: number storeName: string } = { name: 'SVGA.DB', version: 1.0, storeName: 'files' }) ``` -------------------------------- ### Cache-then-use pattern with DB.find, Parser, and Player Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/db.md Caches a parsed SVGA resource in the database and reuses it on subsequent loads. Requires Parser to be created with isDisableImageBitmapShim: true because ImageBitmap data cannot be JSON-serialized into the DB. The example shows the full workflow: find, parse, insert, mount, and start the player, with try/catch error logging. ```javascript import { Parser, Player, DB } from 'svga' const url = 'https://example.com/xx.svga' const db = new DB() try { let svga = await db.find(url) if (!svga) { // Parser must disable the ImageBitmap shim: ImageBitmap data cannot be // stored in the DB (values are JSON-serialized). const parser = new Parser({ isDisableImageBitmapShim: true }) svga = await parser.load(url) await db.insert(url, svga) } const player = new Player(document.getElementById('canvas')) await player.mount(svga) player.start() } catch (error) { console.error(error) } ``` -------------------------------- ### Movie interface Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/types.md Raw movie entity. Input to VideoEntity constructor and produced by protobuf decode of com.opensource.svga.MovieEntity. Worker skips image keys starting with 'audio'. ```ts export interface Movie { version: string images: { [key: string]: Uint8Array } params: { fps: number frames: number viewBoxHeight: number viewBoxWidth: number } sprites: MovieSprite[] } ``` -------------------------------- ### Basic playback with event callbacks Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/player.md Demonstrates how to load an SVGA file using the Parser and initialize the Player with various event listeners for playback lifecycle tracking. ```js import { Parser, Player } from 'svga' const parser = new Parser() const video = await parser.load('https://example.com/anim.svga') const player = new Player(document.getElementById('canvas')) player.onStart = () => console.log('started') player.onProcess = () => console.log('frame', player.currentFrame, '/', player.totalFrames) player.onEnd = () => console.log('ended') player.onPause = () => console.log('paused') player.onResume = () => console.log('resumed') player.onStop = () => console.log('stopped') await player.mount(video) player.start() // play // player.pause() // pause, then player.resume() // player.stop() // reset to frame 0 // player.clear() // just wipe the canvas // player.destroy() // teardown ``` -------------------------------- ### Configuring playback with frame subsets and modes Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/player.md Shows how to initialize the Player with specific configuration options like loop counts, frame ranges, and fill modes. The setConfig method can be used to update these settings after initialization. ```js import { Parser, Player, PLAYER_PLAY_MODE, PLAYER_FILL_MODE } from 'svga' const parser = new Parser() const video = await parser.load('https://example.com/anim.svga') const player = new Player({ container: document.getElementById('canvas'), loop: 3, startFrame: 10, endFrame: 20, loopStartFrame: 15, fillMode: PLAYER_FILL_MODE.BACKWARDS, playMode: PLAYER_PLAY_MODE.FALLBACKS, isCacheFrames: true, isUseIntersectionObserver: true, isOpenNoExecutionDelay: true }) // setConfig can also adjust options after construction: player.setConfig({ loop: false }) ``` -------------------------------- ### Basic Parse and Play Flow Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/parser.md Standard workflow for loading an SVGA animation and mounting it to a canvas player. ```js import { Parser, Player } from 'svga' const parser = new Parser() const svga = await parser.load('https://example.com/animation.svga') const player = new Player(document.getElementById('canvas')) await player.mount(svga) player.start() ``` -------------------------------- ### Error handling for unsupported environments and deletion with DB and DB.delete Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/db.md Shows synchronous constructor throwing when window.indexedDB is unavailable, with error message '[SVGA.DB] indexedDB not supported'. Also demonstrates db.find returning undefined for missing cache entries and db.delete removing entries. find/insert/delete methods reject with 'find error', 'insert error', 'delete error' on failure. ```javascript import { DB } from 'svga' // Throws synchronously in environments without window.indexedDB: let db try { db = new DB({ name: 'SVGA.DB', version: 1, storeName: 'files' }) } catch (error) { // Error: [SVGA.DB] indexedDB not supported console.error('indexedDB unavailable:', error.message) throw error } const id = 'https://example.com/xx.svga' try { const cached = await db.find(id) // undefined when not cached await db.delete(id) // remove a cache entry } catch (error) { // find/insert/delete reject with 'find error' / 'insert error' / 'delete error' console.error(error.message) } ``` -------------------------------- ### new Parser(options) Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/parser.md Creates a new Parser instance. The constructor accepts an optional ParserConfigOptions object to configure worker usage and image bitmap shimming. ```APIDOC ## new Parser(options) ### Description Creates a new Parser instance. The constructor accepts an optional ParserConfigOptions object to configure worker usage and image bitmap shimming. ### Method Constructor ### Endpoint new Parser(options) ### Parameters #### Constructor Parameters - **options** (ParserConfigOptions) - Optional - Configuration options. Defaults to `{ isDisableWebWorker: false, isDisableImageBitmapShim: false }`. - **isDisableWebWorker** (boolean) - Optional - If true, uses an inlined mock worker instead of a real Web Worker. - **isDisableImageBitmapShim** (boolean) - Optional - If true, images are decoded as base64 strings instead of ImageBitmap objects. ### Behavior - If `isDisableImageBitmapShim` is true, the flag is stored and forwarded to the worker so images are returned as base64 strings. - If `isDisableWebWorker` is true, the code executes the inline worker source via `eval(INLINE_WORKER_FLAG)` and uses `window.SVGAParserMockWorker`. - Otherwise, creates a real `new Worker(window.URL.createObjectURL(new Blob([INLINE_WORKER_FLAG])))`. ### Throws - **Error('SVGAParserMockWorker undefined')** - If `isDisableWebWorker` is true but `window.SVGAParserMockWorker` is not defined. ``` -------------------------------- ### constructor(options: HTMLCanvasElement | PlayerConfigOptions) Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/player.md Creates a new Player instance. Accepts either a canvas element to use as the container or a configuration object with optional settings. Initializes the animator and offscreen render target. ```APIDOC ## constructor(options: HTMLCanvasElement | PlayerConfigOptions) ### Description Creates a new Player instance. Accepts either a canvas element to use as the container or a configuration object with optional settings. Initializes the animator and offscreen render target. ### Method Constructor ### Signature ```ts constructor (options: HTMLCanvasElement | PlayerConfigOptions) ``` ### Parameters #### options - **Type**: `HTMLCanvasElement | PlayerConfigOptions` - **Required**: Yes - **Description**: Either a canvas element to use as the container, or a configuration object. If a canvas element is provided, it is used as-is and configuration stays at defaults. If a `PlayerConfigOptions` object is provided, the `container` field is used if present, otherwise a new canvas is created, and `setConfig(options)` is called. ### PlayerConfigOptions Fields | Field | Type | Default | Description | |-------|------|---------|-------------| | `container` | `HTMLCanvasElement` | `document.createElement('canvas')` | The canvas element to render the animation into. | | `loop` | `number \| boolean` | `0` | Number of loops or boolean indicating whether to loop. | | `fillMode` | `PLAYER_FILL_MODE` | `'forwards'` | Fill mode for the animation. | | `playMode` | `PLAYER_PLAY_MODE` | `'forwards'` | Play mode for the animation. | | `startFrame` | `number` | `0` | The frame at which to start playing. | | `endFrame` | `number` | `0` | The frame at which to end playing. | | `loopStartFrame` | `number` | `0` | The frame at which to start looping. | | `isCacheFrames` | `boolean` | `false` | Whether to cache frames. | | `isUseIntersectionObserver` | `boolean` | `false` | Whether to use IntersectionObserver for visibility. | | `isOpenNoExecutionDelay` | `boolean` | `false` | Whether to disable execution delay. | ### Behavior - Creates an `Animator` and wires `animator.onEnd` to call `this.onEnd`. - Creates the offscreen render target: `new window.OffscreenCanvas(container.width, container.height)` when `OffscreenCanvas` is available, else `document.createElement('canvas')`. ``` -------------------------------- ### mount(videoEntity) Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/player.md Asynchronously prepares the player to render the given Video entity, decoding all sprite images to canvas-drawable elements and initializing playback state. Resolves when all images are decoded, or immediately if there are no images. ```APIDOC ## mount(videoEntity) ### Description Asynchronously mounts a parsed Video entity, decoding all sprite images to canvas-drawable elements and initializing the player state. ### Method mount ### Signature ```ts public async mount (videoEntity: Video): Promise<void> ``` ### Parameters #### videoEntity - **type** (`Video`) - Required - Parsed data from `Parser.load(...)` or a `VideoEntity` instance. ### Return Value `Promise<void>` - Resolves once all sprite images are decoded to canvas-drawable elements. ### Behavior - String images (base64) become `HTMLImageElement` with `src = 'data:image/png;base64,' + image`; resolution waits for each `img.onload`. - Non-string images (`ImageBitmap`, `HTMLImageElement`) are used directly. - Resolves immediately when `videoEntity.images` is empty or when the entity is `undefined`. ### Side Effects - Sets `currentFrame = 0` and `totalFrames = videoEntity.frames - 1`. - Clears the container and resizes the canvas to `videoEntity.size`. - Rebuilds `bitmapsCache`. ``` -------------------------------- ### Animator with loopStart and onEnd teardown Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/animator.md Uses isOpenNoExecutionDelay to enable a worker timer, sets loopStart to 500 ms to restart progress on each loop, and runs 3 passes before onEnd stops the animator. Demonstrates error-free teardown and looping. ```javascript import { Animator } from 'svga/player/animator' const animator = new Animator() animator.isOpenNoExecutionDelay = true // use worker timer animator.startValue = 0 animator.endValue = 60 animator.duration = 2000 animator.loopStart = 500 // restart progress at 500 ms on each loop animator.loop = 3 // run 3 passes then onEnd animator.onEnd = () => { console.log('timeline complete') animator.stop() } animator.start() ``` -------------------------------- ### async load(url): Promise<Video> Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/parser.md Loads and parses an SVGA file from the given URL. Returns a Promise that resolves with a renderable Video entity. ```APIDOC ## async load(url): Promise<Video> ### Description Loads and parses an SVGA file from the given URL. Returns a Promise that resolves with a renderable Video entity. ### Method async load ### Endpoint load(url) ### Parameters #### Method Parameters - **url** (string) - Required - The URL of the SVGA file to load. ### Returns - **Promise<Video>** - A Promise that resolves with a Video object representing the parsed SVGA content. ``` -------------------------------- ### Catch synchronous throws from Player and Parser Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/errors.md Shows how to catch synchronous throws (#1-#11) at the call site. `player.start()` throws #5 'videoEntity undefined' before mount, `player.setConfig({ startFrame: 10, endFrame: 5 })` throws #4, and `new Parser({ isDisableWebWorker: true })` throws #3 if the page was not built with the inline-parser step. ```javascript import { Parser, Player } from 'svga' const player = new Player(document.getElementById('canvas')) try { player.start() // throws #5 'videoEntity undefined' before mount } catch (error) { console.error(error.message) } try { player.setConfig({ startFrame: 10, endFrame: 5 }) // throws #4 } catch (error) { console.error(error.message) } try { const parser = new Parser({ isDisableWebWorker: true }) // throws #3 if the page was not built with the inline-parser step } catch (error) { console.error(error.message) } ``` -------------------------------- ### DB Class Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/db.md Overview of the DB class constructor and its configuration options. ```APIDOC ## DB Class ### Description Persistent cache for parsed Video entities backed by IndexedDB. Stores JSON.stringify(Video) strings keyed by arbitrary IDs. ### Constructor #### Parameters - **name** (string) - Optional - Default: 'SVGA.DB' - IndexedDB database name - **version** (number) - Optional - Default: 1.0 - Database version; if schema upgrade needed, store is created with db.createObjectStore(storeName) - **storeName** (string) - Optional - Default: 'files' - Object store used for all records #### Notes - Constructor starts opening the database asynchronously (dbPromise). - If window.indexedDB is undefined, throws synchronously: Error('[SVGA.DB] indexedDB not supported') - If open request errors, the dbPromise rejects with: Error('[SVGA.DB] indexedDB open fail, <error.type>') ``` -------------------------------- ### Catch async parser and DB errors with try/catch Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/errors.md Shows how to catch asynchronous parser and DB rejections using try/catch around await. Parser failures (#12-#14) and DB failures (#15-#18) are standard Error instances; #11 is a synchronous throw from `new DB()` and must be wrapped separately. ```javascript import { Parser, DB } from 'svga' // #12, #13, #14 — parser failures try { const parser = new Parser() const video = await parser.load('https://example.com/broken.svga') } catch (error) { console.error(error.message) // e.g. '[SVGA Parser Error] this parser only support version@2 of SVGA.' } // #15, #16, #17, #18 — DB failures // #11 is a synchronous throw from `new DB()` let db try { db = new DB() } catch (error) { console.error(error.message) // '[SVGA.DB] indexedDB not supported' } try { const cached = await db.find('https://example.com/broken.svga') } catch (error) { console.error(error.message) // 'find error' } ``` -------------------------------- ### load(url) Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/parser.md Downloads the SVGA file over the network and parses it. Returns a Promise that resolves with the parsed animation entity or rejects with an error. ```APIDOC ## load(url) ### Description Downloads the SVGA file over the network and parses it. Returns a Promise that resolves with the parsed animation entity or rejects with an error. ### Method load ### Signature async load (url: string): Promise<Video> ### Parameters - **url** (string) - Required - SVGA file URL. Relative URLs are resolved to absolute against the document base using `<a>` href resolution. ### Return Value - **Promise<Video>** - Resolves with the parsed animation entity. Rejects with an Error whose message is prefixed `[SVGA Parser Error]` for failures inside the worker. ### Throws (Synchronous) - **Error('url undefined')** - Thrown when `url` is `undefined`. - **Error('Parser Worker not found')** - Thrown when `this.worker` is `undefined`. ### Rejections (Rejected Promise) - **Error('[SVGA Parser Error] XMLHttpRequest, <statusText>')** - Rejected when HTTP response is not 200/304 or download failed. - **Error('[SVGA Parser Error] this parser only support version@2 of SVGA.')** - Rejected when the file header is not a v2 SVGA. - **Error('[SVGA Parser Error] <message>')** - Rejected on any decode/inflate error inside the worker. ``` -------------------------------- ### Manual VideoEntity construction from Movie Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/video-entity.md Shows manual construction of VideoEntity from an already-decoded Movie object, e.g., when using the schema directly with protobufjs. Requires a Movie instance and an images object mapping sprite keys to base64 PNG payloads. Access frames and sprite imageKey. ```javascript import { VideoEntity } from 'svga/parser/video-entity' // module path in src // import { Root } from 'protobufjs' // const movie = proto.lookupType('com.opensource.svga.MovieEntity').decode(...) // const movie: Movie = ... const images = { spriteKey: 'iVBORw0KGgo...' } // base64 PNG payloads const video = new VideoEntity(movie, images) console.log(video.frames) // total frames console.log(video.sprites[0].imageKey) // image key per sprite ``` -------------------------------- ### Utils.getVersion(data) Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/utils.md Detects the SVGA file version from the first four header bytes. Returns 1 if the bytes match the ZIP local file header signature (PK\x03\x04), otherwise returns 2. ```APIDOC ## Utils.getVersion(data) ### Description Detects the SVGA file version from the first four header bytes. Returns 1 if the bytes match the ZIP local file header signature (PK\x03\x04), otherwise returns 2. ### Method Function call ### Endpoint `Utils.getVersion(data)` ### Parameters #### Parameters - **data** (ArrayBuffer) - Required - Raw file bytes (e.g. the downloaded SVGA buffer) ### Return Value - **number** - `1` when the first four bytes are `[80, 75, 3, 4]`; `2` otherwise. ### Usage Example ts import { Utils } from './utils' // module path in src const buffer = await fetch('https://example.com/x.svga').then(r => r.arrayBuffer()) const version = Utils.getVersion(buffer) console.log(version) // 2 for files this parser can handle, 1 for legacy SVGA packages ### Notes - No throws are defined in `Utils` itself. - The byte pattern `[80, 75, 3, 4]` corresponds to the ASCII characters `P` and `K` followed by `3` and `4`, completing the little-endian ZIP local file header signature (`PK\x03\x04`, i.e. `0x504B0304`). ``` -------------------------------- ### Parser constructor Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/parser.md Creates a new Parser instance. Options can disable web workers and image bitmap shim. ```APIDOC ## Parser constructor ### Description Creates a new Parser instance. Options can disable web workers and image bitmap shim. ### Method constructor ### Signature new Parser(options?: { isDisableWebWorker?: boolean; isDisableImageBitmapShim?: boolean }) ### Parameters - **options** (object) - Optional - Configuration options. - **isDisableWebWorker** (boolean) - Optional - If true, runs parsing on the main thread instead of a web worker. - **isDisableImageBitmapShim** (boolean) - Optional - If true, images are base64 strings instead of ImageBitmap objects. ``` -------------------------------- ### PlayerConfig Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/types.md Configuration interface for the Player. ```APIDOC ## PlayerConfig ### Description Configuration interface for the Player. ### Fields - `container` (HTMLCanvasElement) - Required - Target canvas - `loop` (number | boolean) - Required - `0`/`true` = endless, `false` = 1 pass, else count - `fillMode` (PLAYER_FILL_MODE) - Required - End-state rule (`'backwards'` → finish on first frame) - `playMode` (PLAYER_PLAY_MODE) - Required - Direction (reverse plays the range backwards) - `startFrame` (number) - Required - First frame - `endFrame` (number) - Required - Last frame (`0` = run to end) - `loopStartFrame` (number) - Required - Loop restart frame; ignored when `<= startFrame` - `isCacheFrames` (boolean) - Required - Cache rendered frames for replay - `isUseIntersectionObserver` (boolean) - Required - Skip rendering when the container is off-screen - `isOpenNoExecutionDelay` (boolean) - Required - Use worker timer to avoid background-tab stalling ### Usage Exposed as `Player.config` (readonly, resolved); accepted by `Player` constructor / `Player.setConfig` via `PlayerConfigOptions`. ``` -------------------------------- ### setConfig(options) Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/player.md Merges the provided partial configuration into the player's current config, updates the internal Animator's delay setting, and reinitializes the intersection observer. Throws an error if startFrame is greater than endFrame. ```APIDOC ## setConfig(options) ### Description Merges each option into `this.config`, propagates `isOpenNoExecutionDelay` to the internal `Animator`, and re-runs intersection-observer setup. ### Method setConfig ### Signature ```ts public setConfig (options: PlayerConfigOptions): void ``` ### Parameters #### options - **type** (`PlayerConfigOptions`) - Required - Partial config; every present key overrides the current value, absent keys fall back to defaults. ### Throws - **Error** - Throws `Error('StartFrame should > EndFrame')` when both `startFrame` and `endFrame` are provided and `startFrame > endFrame`. ``` -------------------------------- ### Parser.load() Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/parser.md Loads an SVGA animation from a URL. Returns a Promise that resolves with the parsed VideoEntity or rejects with an Error. ```APIDOC ## Parser.load() ### Description Loads an SVGA animation from a URL. Returns a Promise that resolves with the parsed VideoEntity or rejects with an Error. ### Method load ### Signature public async load(url: string): Promise<VideoEntity> ### Parameters - **url** (string) - Required - The URL of the SVGA file to load. ### Return Value Promise<VideoEntity> - Resolves with the parsed VideoEntity instance. ### Errors - Error: [SVGA Parser Error] this parser only support version@2 of SVGA. - Error: [SVGA Parser Error] XMLHttpRequest, Not Found ``` -------------------------------- ### Player class Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/player.md Core class for playback of SVGA animations. Constructor accepts either an HTMLCanvasElement or a PlayerConfigOptions object. ```APIDOC ## Player class ### Description Canvas playback engine for a parsed Video entity. ### Class Signature ```ts export class Player { public currentFrame: number = 0 public totalFrames: number = 0 public videoEntity: Video | undefined = undefined public readonly config: PlayerConfig = { ... } constructor(options: HTMLCanvasElement | PlayerConfigOptions) public setConfig(options: PlayerConfigOptions): void public async mount(videoEntity: Video): Promise<void> public onStart: EventCallback public onResume: EventCallback public onPause: EventCallback public onStop: EventCallback public onProcess: EventCallback public onEnd: EventCallback public start(): void public resume(): void public pause(): void public stop(): void public clear(): void public destroy(): void } ``` ### Constructor `constructor(options: HTMLCanvasElement | PlayerConfigOptions)` ### Methods #### setConfig(options: PlayerConfigOptions): void - **options** (PlayerConfigOptions) - Required - Configuration options to update. #### mount(videoEntity: Video): Promise<void> - **videoEntity** (Video) - Required - The parsed video entity to mount. #### start(): void Starts playback. #### resume(): void Resumes playback. #### pause(): void Pauses playback. #### stop(): void Stops playback. #### clear(): void Clears the canvas. #### destroy(): void Destroys the player and nulls internal fields. ### Event Callbacks These are public properties that can be assigned callback functions. - `onStart: EventCallback` - `onResume: EventCallback` - `onPause: EventCallback` - `onStop: EventCallback` - `onProcess: EventCallback` - `onEnd: EventCallback` ### Public Properties | Property | Type | Default | Description | |----------|------|---------|-------------| | `currentFrame` | `number` | `0` | Frame currently being drawn | | `totalFrames` | `number` | `0` | Set to `videoEntity.frames - 1` on mount | | `videoEntity` | `Video \| undefined` | `undefined` | Mounted animation data | | `config` | `PlayerConfig` (readonly) | all defaults | Resolved configuration; mutated by `setConfig` | ### Notes `Player.destroy()` nulls internal fields; the README's `player.progress` property does not exist in source — use `player.currentFrame` instead. ``` -------------------------------- ### Error Handling and Cleanup Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/parser.md Demonstrates running the parser on the main thread and ensuring worker termination in a finally block. ```js import { Parser } from 'svga' const parser = new Parser({ isDisableWebWorker: true }) // run on main thread try { const svga = await parser.load('missing.svga') // ... } catch (error) { // Parser worker failures surface as: // Error: [SVGA Parser Error] this parser only support version@2 of SVGA. // Error: [SVGA Parser Error] XMLHttpRequest, Not Found console.error(error) } finally { parser.destroy() // terminates the Worker } ``` -------------------------------- ### Parser constructor Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/parser.md The constructor signature for initializing the Parser with configuration options. ```ts constructor (options: ParserConfigOptions = { isDisableWebWorker: false, isDisableImageBitmapShim: false }) ``` -------------------------------- ### Utils.getVersion - SVGA version detection Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/utils.md Defines the Utils object with a single getVersion method that inspects the first four bytes of an ArrayBuffer. Returns 1 for ZIP-based SVGA 1.x files (header bytes 80, 75, 3, 4) and 2 otherwise. This is the sole gate that rejects legacy SVGA 1.x packages. ```typescript const getVersion = (data: ArrayBuffer): number => { const dataHeader = new Uint8Array(data, 0, 4) if (dataHeader[0] === 80 && dataHeader[1] === 75 && dataHeader[2] === 3 && dataHeader[3] === 4) { return 1 } return 2 } export const Utils = { getVersion } ``` -------------------------------- ### DynamicElements interface Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/types.md Maps keys to dynamic elements. Assignment pattern: video.dynamicElements[key] = <element>. ```ts export interface DynamicElements { [key: string]: DynamicElement } ``` -------------------------------- ### Parser.load() returns VideoEntity Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/video-entity.md Shows how Parser.load() returns a VideoEntity instance implementing the Video interface. The video object exposes fps, frames, size, and sprites.length. ```javascript // Parser.load() returns a Video built by the worker as: // worker.postMessage(new VideoEntity(movie, images)) import { Parser } from 'svga' const parser = new Parser() const video = await parser.load('https://example.com/anim.svga') // video is a VideoEntity instance implementing Video console.log(video.fps, video.frames, video.size, video.sprites.length) ``` -------------------------------- ### insert Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/db.md Stores a Video entity in the persistent cache under the given ID. ```APIDOC ## insert ### Description Asynchronously stores a Video entity as a JSON string in the object store under the given ID. ### Method insert(id: IDBValidKey, data: Video): Promise<void> ### Parameters - **id** (IDBValidKey) - Required - The key to store the data under. - **data** (Video) - Required - The Video entity to persist. ### Returns - Promise<void> - Resolves when the insert operation completes. ``` -------------------------------- ### VideoEntity constructor Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/video-entity.md Creates a new VideoEntity instance from a protobuf-decoded Movie and optional decoded images. This constructor is used internally by the parser worker to produce a renderable Video entity. ```APIDOC ## VideoEntity constructor ### Description Creates a new VideoEntity instance from a protobuf-decoded Movie and optional decoded images. This constructor is used internally by the parser worker to produce a renderable Video entity. ### Signature constructor(movie: Movie, images: RawImages = {}) ### Parameters - **movie** (Movie) - Required - The protobuf-decoded raw parsed SVGA movie data. - **images** (RawImages) - Optional - Decoded images keyed by image key. Defaults to an empty object. ### Returns A new VideoEntity instance implementing the Video interface. ### Example ```ts const entity = new VideoEntity(movie, images) ``` ``` -------------------------------- ### Video interface Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/types.md Decoded video entity. Accepted by Parser.load return, Player.mount, DB.find return / DB.insert; implemented by VideoEntity; returned by MockWebWorker.postMessage / onmessageCallback. ```ts export interface Video { version: string size: { width: number height: number } fps: number frames: number images: RawImages replaceElements: ReplaceElements dynamicElements: DynamicElements sprites: VideoSprite[] } ``` -------------------------------- ### resume() Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/player.md Restarts the animation timeline from the current frame without resetting state, then fires onResume. No video check is performed in source. ```APIDOC ## resume() ### Description Restarts the animation timeline from the current frame without resetting state, then fires `onResume`. No video check is performed in source. ### Method `resume()` ### Signature ```ts public resume (): void ``` ``` -------------------------------- ### insert(id, data) method signature Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/db.md Declares the async insert method that stores a Video entity. The data is JSON.stringify'd, so all image payloads must be JSON-serializable (use base64 images). Rejects with Error('insert error') if the put request fails. ```typescript async insert (id: IDBValidKey, data: Video): Promise<void> ``` -------------------------------- ### PlayerConfig interface Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/configuration.md Defines the full Player configuration object. All keys are optional at the call site because PlayerConfigOptions is a Partial of this interface. The defaults are the initial values of Player.config and the fallbacks applied in setConfig. ```typescript export interface PlayerConfig { container: HTMLCanvasElement loop: number | boolean fillMode: PLAYER_FILL_MODE playMode: PLAYER_PLAY_MODE startFrame: number endFrame: number loopStartFrame: number isCacheFrames: boolean isUseIntersectionObserver: boolean isOpenNoExecutionDelay: boolean } ``` -------------------------------- ### ReplaceElements interface Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/types.md Maps keys to replaceable elements. Assignment pattern: video.replaceElements[key] = <element>. ```ts export interface ReplaceElements { [key: string]: ReplaceElement } ``` -------------------------------- ### resume() method signature Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/player.md Signature for the resume() method. Restarts the animation timeline from the current frame without resetting state, then fires onResume. No video check is performed. ```typescript public resume (): void ``` -------------------------------- ### PlayerConfigOptions Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/types.md Type alias making all `PlayerConfig` fields optional. ```APIDOC ## PlayerConfigOptions ### Description Type alias making all `PlayerConfig` fields optional when constructing a `Player` or calling `setConfig`. ### Definition `type PlayerConfigOptions = Partial<PlayerConfig>` ``` -------------------------------- ### find Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/db.md Retrieves a stored Video entity by its ID from the object store. ```APIDOC ## find ### Description Asynchronously retrieves a Video entity from the persistent cache by its ID. ### Method find(id: IDBValidKey): Promise<Video | undefined> ### Parameters - **id** (IDBValidKey) - Required - The key to look up in the object store. ### Returns - Promise<Video | undefined> - Resolves with the parsed Video object if found, otherwise undefined. ``` -------------------------------- ### RectPath interface Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/types.md Defines a rectangle path with position, size, and corner rounding. All fields are required numbers. ```ts // src/types.ts:105-111 export interface RectPath { x: number y: number width: number height: number cornerRadius: number } ``` -------------------------------- ### RawImages interface Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/types.md Maps image keys to base64 PNG payloads or canvas-drawable objects. Used by Video.images. ```ts export interface RawImages { [key: string]: string | HTMLImageElement | ImageBitmap } ``` -------------------------------- ### find(id) Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/db.md Retrieves a stored SVGA video entity by its key. Returns the parsed JSON object or undefined if no string payload exists for the key. ```APIDOC ## find(id) ### Description Retrieves a stored SVGA video entity by its key. Returns the parsed JSON object or undefined if no string payload exists for the key. ### Method find ### Signature ```ts async find (id: IDBValidKey): Promise<Video | undefined> ``` ### Parameters - `id` (IDBValidKey) - Required - Record key (e.g. the SVGA URL string) ### Return `Promise<Video | undefined>` — the stored entity parsed from JSON, or `undefined` when no string payload exists for the key. ### Errors - `Error('find error')` - The read transaction `get(id)` fails (`src/db.ts:39`) ### Implementation Runs in a `'readonly'` transaction; on success, resolves with `JSON.parse(request.result)` when `typeof request.result === 'string'`, else `undefined`. ``` -------------------------------- ### render function signature (TypeScript) Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/render.md The main render function that draws one frame. It takes the canvas, caches for bitmaps, dynamic and replacement elements, the video entity, and the current frame index. Returns void. Throws Error('Render Context cannot be null') if the 2D context is not available, and Error('Render Context is not context2d') if the context lacks a save method. ```TypeScript // src/player/render.ts:27-46 function render ( canvas: HTMLCanvasElement | OffscreenCanvas, bitmapsCache: BitmapsCache, dynamicElements: DynamicElements, replaceElements: ReplaceElements, videoEntity: Video, currentFrame: number ): void export default render // src/player/render.ts:412 ``` -------------------------------- ### insert(id, data) Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/db.md Persists an SVGA video entity to the database. The data is serialized to JSON before storage, so all image payloads must be JSON-serializable. ```APIDOC ## insert(id, data) ### Description Persists an SVGA video entity to the database. The data is serialized to JSON before storage, so all image payloads must be JSON-serializable. ### Method insert ### Signature ```ts async insert (id: IDBValidKey, data: Video): Promise<void> ``` ### Parameters - `id` (IDBValidKey) - Required - Record key - `data` (Video) - Required - Entity to persist. `JSON.stringify(data)` is stored, so all image payloads must be JSON-serializable — use base64 images (constructed `Parser({ isDisableImageBitmapShim: true })`); `ImageBitmap` values would not survive serialization. ### Return `Promise<void>`, resolves on transaction completion. ### Errors - `Error('insert error')` - The `put(...)` request fails (`src/db.ts:48`) ``` -------------------------------- ### find(id) method signature Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/db.md Declares the async find method that retrieves a stored entity by key. Returns a Promise resolving to a Video object or undefined if no string payload exists. Rejects with Error('find error') if the read transaction fails. ```typescript async find (id: IDBValidKey): Promise<Video | undefined> ``` -------------------------------- ### DB class signature (src/db.ts:3-60) Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/db.md Defines the DB class with a private storeName and dbPromise, and a constructor that accepts an optional configuration object with defaults for name, version, and storeName. The class provides async methods find, insert, and delete for IndexedDB operations. ```typescript // src/db.ts:3-60 export class DB { private readonly storeName: string private readonly dbPromise: Promise<IDBDatabase> constructor ({ name, version, storeName }: { name: string version: number storeName: string } = { name: 'SVGA.DB', version: 1.0, storeName: 'files' }) async find (id: IDBValidKey): Promise<Video | undefined> async insert (id: IDBValidKey, data: Video): Promise<void> async delete (id: IDBValidKey): Promise<void> } ``` -------------------------------- ### MockWebWorker interface for parser worker Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/types.md Defines the mock worker interface used by `Parser.worker` (which can be `MockWebWorker | Worker`) and by `window.SVGAParserMockWorker` (declared in `src/global.d.ts` as `undefined | MockWebWorker`). `onmessage` is the entry point, `onmessageCallback` is the result sink set by `Parser.load`, and `postMessage` delivers the result to `onmessageCallback`. ```typescript // src/types.ts:8-13 export interface MockWebWorker { onmessage: (event: { data: ParserPostMessageArgs }) => void onmessageCallback: (data: Video | Error) => void postMessage: (data: Video | Error) => void } ``` -------------------------------- ### PLAYER_PLAY_MODE Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/types.md Enum defining the playback direction. ```APIDOC ## PLAYER_PLAY_MODE ### Description Enum defining the playback direction. ### Members - `FORWARDS` = `'forwards'` - Play in order - `FALLBACKS` = `'fallbacks'` - Play in reverse (note the source spelling) ### Usage Used by `PlayerConfig.playMode`; swaps `startValue`/`endValue` in `Player.startAnimation`. ``` -------------------------------- ### Direct usage of render module Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/render.md The render module can be imported directly from the source path. It requires a valid canvas context and will throw errors if the context is missing or invalid. ```js import render from 'svga/player/render' // module path in src try { render(ofsCanvas, bitmapsCache, {}, {}, video, 0) } catch (error) { // 'Render Context cannot be null' | 'Render Context is not context2d' console.error(error.message) } ``` -------------------------------- ### Parsing with Base64 Images for DB Persistence Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/parser.md Disables ImageBitmapShim to retrieve base64 strings, allowing serialization for database insertion. ```js import { Parser, DB } from 'svga' // isDisableImageBitmapShim must be true so images are base64 strings, // which is what DB.insert() serializes via JSON.stringify. const parser = new Parser({ isDisableImageBitmapShim: true }) const svga = await parser.load('https://example.com/animation.svga') const db = new DB() await db.insert('animation.svga', svga) ``` -------------------------------- ### Player default config constant Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/configuration.md The default configuration values used by the Player. These are the initial values of Player.config and the fallbacks applied in setConfig. The container defaults to a newly created canvas element. ```typescript public readonly config: PlayerConfig = { container: document.createElement('canvas'), loop: 0, fillMode: PLAYER_FILL_MODE.FORWARDS, playMode: PLAYER_PLAY_MODE.FORWARDS, startFrame: 0, endFrame: 0, loopStartFrame: 0, isCacheFrames: false, isUseIntersectionObserver: false, isOpenNoExecutionDelay: false } ``` -------------------------------- ### VideoSprite interface Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/types.md Defines a sprite with converted frames. The imageKey is used to look up the image in images, replaceElements, or dynamicElements. ```ts export interface VideoSprite { imageKey: string frames: VideoFrame[] } ``` -------------------------------- ### clear() Source: https://github.com/svga/svgaplayer-web-lite/blob/master/_autodocs/api-reference/player.md Re-assigns container.width = container.width to wipe the canvas (clearContainer). ```APIDOC ## clear() ### Description Re-assigns `container.width = container.width` to wipe the canvas (`clearContainer`). ### Method `clear()` ### Signature ```ts public clear (): void ``` ```