SVGAPlayer-Web-Lite

repository·master·Indexed 18 days ago

https://github.com/svga/svgaplayer-web-lite

A lightweight and efficient SVGA player for mobile web environments. It features multi-threaded parsing via WebWorkers and supports modern web APIs such as OffscreenCanvas and ImageBitmap. The library provides a Parser for loading .svga files, a Player for rendering animations onto a <canvas> element, and a DB class for persisting parsed data in IndexedDB.

Tokens
4.3K
Snippets
19
Records
22
Agent score
62%

What's inside svga-svgaplayer-web-lite

  1. Configure Vite to handle .svga files

    master

    In Vite, you can treat .svga files as static assets by adding them to assetsInclude in your configuration. Use the ?url suffix to import the file path.

    // vite.config.ts
    import { defineConfig } from 'vite'
    
    export default defineConfig({
      assetsInclude: [
        'svga'
      ]
    })
    
    // Usage in JS
    import { Parser } from 'svga'
    import xx from './xx.svga?url'
    const parser = new Parser()
    const svga = await parser.load(xx)
  2. Cache parsed SVGA data using DB (IndexedDB)

    master

    To avoid re-downloading and re-parsing the same SVGA files, use the DB class to persist the parsed data in IndexedDB.

    Note: When using DB, you must set isDisableImageBitmapShim: true in the Parser configuration because ImageBitmap data cannot be stored directly in IndexedDB.

    import { Parser, DB } from 'svga'
    
    try {
      const url = 'xx.svga'
      const db = new DB()
      let svga = await db.find(url)
    
      if (!svga) {
        // Must disable ImageBitmap shim to allow storage in IndexedDB
        const parser = new Parser({ isDisableImageBitmapShim: true })
        svga = await parser.load(url)
        await db.insert(url, svga)
      }
    
      await player.mount(svga)
    } catch (error) {
      console.error(error)
    }
  3. Replace or insert dynamic elements in SVGA

    master

    You can modify the parsed SVGA data before mounting it to the player. This allows you to swap images or inject dynamic content like text rendered to a canvas.

    const svga = await parser.load('xx.svga')
    
    // Replace an element using a key
    const image = new Image()
    image.src = 'https://xxx.com/xxx.png'
    svga.replaceElements['key'] = image
    
    // Insert a dynamic element (e.g., text rendered to a canvas)
    const text = 'hello gg'
    const fontCanvas = document.createElement('canvas')
    const fontContext = fontCanvas.getContext('2d')
    // ... setup fontCanvas context ...
    fontContext.fillText(text, fontCanvas.clientWidth / 2, fontCanvas.clientHeight / 2)
    
    svga.dynamicElements['key'] = fontCanvas
    
    await player.mount(svga)
  4. Configure Webpack to handle .svga files

    master

    To import .svga files directly in your JavaScript/TypeScript code using Webpack, use url-loader (or raw-loader) in your configuration.

    // webpack.config.js
    module.exports = {
      module: {
        rules: [
          {
            test: /\.svga$/i,
            use: 'url-loader'
          }
        ]
      }
    }
    
    // Usage in JS
    import { Parser } from 'svga'
    import xx from './xx.svga'
    const parser = new Parser()
    const svga = await parser.load(xx)
  5. Install SVGAPlayer-Web-Lite via NPM or CDN

    master

    You can install the svga package using a package manager or include it directly in your HTML via a CDN.

    NPM

    Use yarn or npm to add the package to your project.

    CDN

    Include the following script tag in your HTML file to use the library via unpkg.

    yarn add svga
    # or
    npm i svga
    <script src="https://unpkg.com/svga/dist/index.min.js"></script>
  6. Understand Player playback modes and fill modes

    master

    The player uses specific enums to determine how an animation behaves when it reaches its end or how it sequences frames.

    Fill Modes (PLAYER_FILL_MODE)

    Determines which frame the animation stays on after playback completes (similar to CSS animation-fill-mode).

    • FORWARDS: Stay on the first frame.
    • BACKWARDS: Stay on the last frame.

    Play Modes (PLAYER_PLAY_MODE)

    Determines the playback direction.

    • FORWARDS: Sequential playback.
    • FALLBACKS: Reverse playback.
  7. Configure the Player with PlayerConfigOptions

    master

    The Player constructor accepts several options to control playback behavior, looping, and performance optimizations.

    Enums

    • PLAYER_FILL_MODE: Defines where the animation stops after finishing.
      • FORWARDS: Stops on the first frame.
      • BACKWARDS: Stops on the last frame.
    • PLAYER_PLAY_MODE: Defines the playback direction.
      • FORWARDS: Sequential playback.
      • FALLBACKS: Reverse playback.

    Options

    OptionTypeDefaultDescription
    containerHTMLCanvasElementThe canvas element for rendering.
    loopnumber | boolean0Number of loops. 0 or true means infinite loop.
    fillModePLAYER_FILL_MODEforwardsTarget mode after playback ends.
    playModePLAYER_PLAY_MODEforwardsPlayback direction.
    startFramenumber0The frame to start playback from.
    endFramenumber0The frame to end playback at.
    loopStartFramenumber0The frame to jump to when looping. Must be $\ge$ startFrame.
    isCacheFramesbooleanfalseCaches drawn frames to improve repeat playback performance.
    isUseIntersectionObserverbooleanfalseUses Intersection Observer to stop rendering when the canvas is off-screen.
    isOpenNoExecutionDelaybooleanfalseUses WebWorker to ensure timely execution even if the browser delays tasks.
    // Example configuration
    new Player({
      container: document.getElementById('canvas') as HTMLCanvasElement,
      loop: 1,
      fillMode: 'forwards',
      playMode: 'forwards',
      isCacheFrames: true,
      isUseIntersectionObserver: true
    })
  8. Configure the Parser with ParserConfigOptions

    master

    The Parser constructor accepts an options object to control internal optimizations like WebWorker usage and ImageBitmap shims.

    new Parser({
      // Whether to disable WebWorker usage. Default: false
      isDisableWebWorker: false,
    
      // Whether to disable the ImageBitmap shim. Default: false
      isDisableImageBitmapShim: false
    })
  9. Basic usage of Parser and Player

    master

    To play an SVGA animation, you need to use the Parser to load the file and the Player to render it onto a <canvas> element. The Parser handles the data loading, and the Player manages the playback lifecycle and events.

    import { Parser, Player } from 'svga'
    
    // 1. Setup canvas
    // <canvas id="canvas"></canvas>
    
    // 2. Parse the SVGA file
    const parser = new Parser()
    const svga = await parser.load('xx.svga')
    
    // 3. Initialize and mount the player
    const player = new Player(document.getElementById('canvas'))
    await player.mount(svga)
    
    // 4. Handle playback events
    player.onStart = () => console.log('onStart')
    player.onResume = () => console.log('onResume')
    player.onPause = () => console.log('onPause')
    player.onStop = () => console.log('onStop')
    player.onProcess = () => console.log('onProcess', player.progress)
    player.onEnd = () => console.log('onEnd')
    
    // 5. Control playback
    player.start()
    // player.pause()
    // player.resume()
    // player.stop()
    // player.clear()
    
    // Cleanup
    // parser.destroy()
    // player.destroy()
  10. Configure the Parser with ParserConfigOptions

    master

    The Parser class is initialized using a ParserConfigOptions object. This allows you to control how the background worker and image processing shims behave.

    Available options:

    • isDisableWebWorker: If set to true, the parser will use a mock worker instead of a real Web Worker. This is useful for environments where Web Workers are not supported or for testing.
    • isDisableImageBitmapShim: If set to true, it disables the ImageBitmap shim.
    import { Parser, ParserConfigOptions } from 'svga';
    
    const options: ParserConfigOptions = {
      isDisableWebWorker: false,
      isDisableImageBitmapShim: false
    };
    
    const parser = new Parser(options);
  11. Configure the SVGAPlayer with PlayerConfig

    master

    When initializing the player, you can provide a PlayerConfig object to control playback behavior. Common options include setting the target canvas, loop count, and playback modes.

    const config: PlayerConfig = {
      container: myCanvasElement,
      loop: 1,
      fillMode: PLAYER_FILL_MODE.FORWARDS,
      playMode: PLAYER_PLAY_MODE.FORWARDS,
      startFrame: 0,
      endFrame: 100,
      isCacheFrames: true,
      isUseIntersectionObserver: true,
      isOpenNoExecutionDelay: true
    };
  12. Handle Player lifecycle events

    master

    You can attach callback functions to the Player instance to react to animation state changes:

    • onStart: Triggered when playback begins.
    • onResume: Triggered when playback is resumed after a pause.
    • onPause: Triggered when playback is paused.
    • onStop: Triggered when playback is stopped.
    • onProcess: Triggered during every frame update (useful for progress tracking).
    • onEnd: Triggered when the animation reaches its end or completes its loop count.
    player.onStart = () => console.log('Animation started');
    player.onProcess = () => console.log('Processing frame...');
    player.onEnd = () => console.log('Animation finished');