### Install and Run Parcel Example Source: https://github.com/rive-app/rive-wasm/blob/master/wasm/examples/parcel_example/README.md Follow these commands to install dependencies and start the development server for the Parcel example. Parcel automatically rebuilds on changes, but runtime changes require a manual rebuild. ```bash cd wasm ./build_all_wasm.sh cd examples/parcel_example npm install npm run start ``` -------------------------------- ### Run Parcel Example App (High-Level API) Source: https://github.com/rive-app/rive-wasm/blob/master/CONTRIBUTING.md Navigate to the parcel example directory, install dependencies, and start the development server to test changes to the high-level API. ```bash cd js/examples/_frameworks/parcel_example_canvas npm i npm start ``` -------------------------------- ### Start Development Server Source: https://github.com/rive-app/rive-wasm/blob/master/js/examples/_frameworks/spotify-player-app/README.md Installs dependencies and starts a local development server for the SvelteKit app. Use the --open flag to automatically open the app in a new browser tab. ```bash npm run dev # or start the server and open the app in a new browser tab npm run dev -- --open ``` -------------------------------- ### Build and Run Rive WASM Example Source: https://github.com/rive-app/rive-wasm/blob/master/wasm/examples/out_of_band_example/README.md Instructions to build the Rive WASM runtime and start the out-of-band example project. Ensure you have the necessary build tools and Node.js installed. ```bash cd wasm ./build_all_wasm.sh cd examples/out_of_band_example npm i npm start ``` -------------------------------- ### Build and Run Rive Layouts Example Source: https://github.com/rive-app/rive-wasm/blob/master/wasm/examples/layout_example/README.md Instructions to build the Wasm runtime and start the layout example using npm. ```bash cd wasm ./build_all_wasm.sh cd examples/layout npm i npm start ``` -------------------------------- ### Install Dependencies and Build Runtime Source: https://github.com/rive-app/rive-wasm/blob/master/js/examples/_frameworks/vite_canvas_centered/README.md Build the canvas runtime and install example dependencies. Ensure you are in the correct directories for building the runtime and installing example packages. ```bash # Build the canvas runtime (from runtime_wasm root or repo root as needed) cd packages/runtime_wasm/wasm && ./build_all_wasm.sh cd ../../js/examples/_frameworks/vite_canvas_centered npm install ``` -------------------------------- ### Run Parcel Example App (Low-Level API) Source: https://github.com/rive-app/rive-wasm/blob/master/CONTRIBUTING.md Navigate to the parcel example directory for low-level API development, install dependencies, and start the development server to test changes. ```bash cd wasm/examples/parcel_example npm i npm start ``` -------------------------------- ### Build and Run Centaur Game Example Source: https://github.com/rive-app/rive-wasm/blob/master/wasm/examples/centaur_game/README.md Instructions to build the Rive WASM runtime and start the Centaur Game example locally. Ensure you are in the correct directories and have installed dependencies. ```bash cd js ./build.sh cd examples/centaur_game npm i npm start ``` -------------------------------- ### Install @rive-app/canvas-advanced-single Source: https://github.com/rive-app/rive-wasm/blob/master/js/npm/canvas_advanced_single/README.md Install the package using npm. ```bash npm install @rive-app/canvas-advanced-single ``` -------------------------------- ### Install Canvas Advanced Lite Source: https://github.com/rive-app/rive-wasm/blob/master/js/npm/canvas_advanced_lite/README.md Install the @rive-app/canvas-advanced-lite package using npm. ```bash npm install @rive-app/canvas-advanced-lite ``` -------------------------------- ### Run Development Server Source: https://github.com/rive-app/rive-wasm/blob/master/js/examples/_frameworks/vite_canvas_centered/README.md Start the Vite development server to view the Rive animation. Open the provided URL in your browser. ```bash npm run dev ``` -------------------------------- ### Install @rive-app/canvas-lite Source: https://github.com/rive-app/rive-wasm/blob/master/js/npm/canvas_lite/README.md Install the Rive Canvas Lite package using npm. This package is a lightweight alternative to the full Rive Canvas renderer. ```bash npm install @rive-app/canvas-lite ``` -------------------------------- ### Install Rive Canvas Single Source: https://github.com/rive-app/rive-wasm/blob/master/js/npm/canvas_single/README.md Install the Rive Canvas Single package using npm. This package provides a high-level API for Rive animations using CanvasRenderingContext2D. ```bash npm install @rive-app/canvas-single ``` -------------------------------- ### new Rive(params: RiveParameters) Source: https://context7.com/rive-app/rive-wasm/llms.txt Instantiates a Rive player that loads a .riv file, creates a renderer, starts the animation loop, and fires lifecycle events. It accepts various parameters for customization, including the source file, canvas, autoplay, state machines, layout, and event callbacks. ```APIDOC ## new Rive(params: RiveParameters) ### Description Instantiates a Rive player that loads a `.riv` file (from a URL or `ArrayBuffer`), creates a renderer on the provided canvas, starts the animation loop, and fires lifecycle events. Accepts optional artboard, animation/state machine names, layout, asset loaders, and event callbacks directly in the constructor. ### Method ```typescript new Rive(params: RiveParameters) ``` ### Parameters #### `params` (RiveParameters) - **src** (string) - URL to .riv file (or use `buffer` for ArrayBuffer) - **canvas** (HTMLCanvasElement) - The canvas element to render on. - **autoplay** (boolean) - Whether to start the animation automatically. - **stateMachines** (string) - name of state machine to run. - **layout** (Layout) - Configuration for fitting and alignment of the artboard. - **onLoad** (function) - Callback function when the Rive file is loaded. - **onLoadError** (function) - Callback function when there is an error loading the Rive file. - **onPlay** (function) - Callback function when the animation starts playing. - **onPause** (function) - Callback function when the animation is paused. - **onStop** (function) - Callback function when the animation is stopped. - **onLoop** (function) - Callback function when the animation loops. - **onStateChange** (function) - Callback function when the state changes in the state machine. - **onAdvance** (function) - Callback function when the animation advances. ### Request Example ```typescript import { Rive, Fit, Alignment, Layout, EventType } from "@rive-app/canvas"; const canvas = document.getElementById("rive-canvas") as HTMLCanvasElement; const r = new Rive({ src: "/animations/hero.riv", // URL to .riv file (or use `buffer` for ArrayBuffer) canvas, autoplay: true, stateMachines: "Main State Machine", // name of state machine to run layout: new Layout({ fit: Fit.Contain, alignment: Alignment.Center, }), onLoad: () => { // Canvas drawing surface should be resized after load for correct DPR scaling r.resizeDrawingSurfaceToCanvas(); console.log("Artboard:", r.activeArtboard); console.log("Animations:", r.animationNames); console.log("State machines:", r.stateMachineNames); }, onLoadError: (e) => console.error("Failed to load:", e.data), onPlay: (e) => console.log("Playing:", e.data), onPause: (e) => console.log("Paused:", e.data), onStop: (e) => console.log("Stopped:", e.data), onLoop: (e) => console.log("Looped:", e.data), // e.data is a LoopEvent onStateChange: (e) => console.log("State changed:", e.data), // e.data is string[] onAdvance: (e) => console.log("Advanced by (s):", e.data), }); // Later: clean up all WASM-allocated objects // r.cleanup(); ``` ``` -------------------------------- ### Install Rive Canvas Package Source: https://github.com/rive-app/rive-wasm/blob/master/js/npm/canvas/README.md Install the Rive Canvas package using npm. This package provides a high-level API for rendering Rive animations with a CanvasRenderingContext2D. ```bash npm install @rive-app/canvas ``` -------------------------------- ### Build Production Version Source: https://github.com/rive-app/rive-wasm/blob/master/js/examples/_frameworks/neostream-events/README.md Use this command to create a production-ready build of your application. ```bash npm run build ``` -------------------------------- ### Build and Preview for Production Source: https://github.com/rive-app/rive-wasm/blob/master/js/examples/_frameworks/vite_canvas_centered/README.md Build the Vite application for production and preview it. This is useful for testing the production build before deployment. ```bash npm run build npm run preview ``` -------------------------------- ### Instantiate Rive Player and Load Animation Source: https://context7.com/rive-app/rive-wasm/llms.txt Use the `Rive` constructor to load a `.riv` file, set up the canvas, and configure playback options. Event callbacks for load, play, pause, stop, loop, state changes, and advance are supported. Ensure `resizeDrawingSurfaceToCanvas()` is called after load for correct display. ```typescript import { Rive, Fit, Alignment, Layout, EventType } from "@rive-app/canvas"; const canvas = document.getElementById("rive-canvas") as HTMLCanvasElement; const r = new Rive({ src: "/animations/hero.riv", // URL to .riv file (or use `buffer` for ArrayBuffer) canvas, autoplay: true, stateMachines: "Main State Machine", // name of state machine to run layout: new Layout({ fit: Fit.Contain, alignment: Alignment.Center, }), onLoad: () => { // Canvas drawing surface should be resized after load for correct DPR scaling r.resizeDrawingSurfaceToCanvas(); console.log("Artboard:", r.activeArtboard); console.log("Animations:", r.animationNames); console.log("State machines:", r.stateMachineNames); }, onLoadError: (e) => console.error("Failed to load:", e.data), onPlay: (e) => console.log("Playing:", e.data), onPause: (e) => console.log("Paused:", e.data), onStop: (e) => console.log("Stopped:", e.data), onLoop: (e) => console.log("Looped:", e.data), // e.data is a LoopEvent onStateChange: (e) => console.log("State changed:", e.data), // e.data is string[] onAdvance: (e) => console.log("Advanced by (s):", e.data), }); // Later: clean up all WASM-allocated objects // r.cleanup(); ``` -------------------------------- ### Basic Canvas Styling for Rive WASM Source: https://github.com/rive-app/rive-wasm/blob/master/js/examples/_frameworks/layout_example/index.html Applies basic CSS to the body and canvas elements to ensure the canvas fills the viewport and has a red background. This is a common setup for full-screen Rive animations. ```css body { background: #f0f0f0; margin: 0; overflow: hidden; } canvas { background-color: red; display: block; width: 100vw; height: 100vh; } ``` -------------------------------- ### Configure Custom WASM Loading Source: https://context7.com/rive-app/rive-wasm/llms.txt Manages fetching and initializing the WASM module. Allows overriding the WASM URL, supplying the binary directly, or configuring a fallback URL. Use for self-hosting, specific CDNs, or bundling WASM with build tools. ```typescript import { RuntimeLoader, Rive } from "@rive-app/canvas"; // Option A: point to a self-hosted WASM file RuntimeLoader.setWasmUrl("/static/rive.wasm"); // Option B: disable the fallback entirely RuntimeLoader.setWasmFallbackUrl(null); // Option C: inline the WASM binary (e.g. bundled as a base64 data URL or fetched ahead of time) const wasmRes = await fetch("/static/rive.wasm"); RuntimeLoader.setWasmBinary(await wasmRes.arrayBuffer()); // Option D: await the runtime directly for advanced use const runtime = await RuntimeLoader.awaitInstance(); console.log("WASM runtime ready:", typeof runtime.makeRenderer); // After configuring the loader, construct Rive as normal const r = new Rive({ src: "/anim.riv", canvas: document.getElementById("c") as HTMLCanvasElement, autoplay: true, }); ``` -------------------------------- ### Build WASM Submodules Source: https://github.com/rive-app/rive-wasm/blob/master/CONTRIBUTING.md Execute the build script to compile all WASM submodules. This can be a lengthy process. ```bash # Top level of the project cd js npm test ``` -------------------------------- ### Shared File Loading: RiveFile Constructor Source: https://context7.com/rive-app/rive-wasm/llms.txt Pre-loads and parses a `.riv` file once, allowing it to be shared across multiple Rive instances on different canvases, optimizing performance by avoiding redundant loading. ```APIDOC ## `new RiveFile(params: RiveFileParameters)` — Share a loaded file across multiple `Rive` instances Pre-loads and parses a `.riv` file once, then hands it to multiple `Rive` instances on different canvases. This avoids re-fetching and re-parsing the same binary for multi-canvas scenarios. ```typescript import { RiveFile, Rive, EventType, Fit, Alignment, Layout } from "@rive-app/canvas"; const sharedFile = new RiveFile({ src: "/character.riv", enableRiveAssetCDN: true, onLoad: () => { // File loaded — now create two Rive instances from the same parsed file const r1 = new Rive({ riveFile: sharedFile, canvas: document.getElementById("canvas-1") as HTMLCanvasElement, artboard: "CharacterA", stateMachines: "Main", autoplay: true, layout: new Layout({ fit: Fit.Contain, alignment: Alignment.Center }), }); const r2 = new Rive({ riveFile: sharedFile, canvas: document.getElementById("canvas-2") as HTMLCanvasElement, artboard: "CharacterB", stateMachines: "Main", autoplay: true, layout: new Layout({ fit: Fit.Contain, alignment: Alignment.Center }), }); // Cleanup both when done window.addEventListener("unload", () => { r1.cleanup(); r2.cleanup(); }); }, onLoadError: (e) => console.error("File load failed:", e.data), }); sharedFile.init(); ``` ``` -------------------------------- ### rive.volume, rive.artboardWidth, rive.artboardHeight Source: https://context7.com/rive-app/rive-wasm/llms.txt Runtime properties that can be read or written to control audio playback volume and override the artboard's intrinsic size for responsive layouts. ```APIDOC ## rive.volume / rive.artboardWidth / rive.artboardHeight — Runtime property setters ### Description Properties that can be read or written at any time after construction. `volume` controls audio playback level (0–1). `artboardWidth` and `artboardHeight` override the artboard's intrinsic size, useful for responsive or dynamically-sized layouts. ### Usage ```typescript // Mute audio r.volume = 0; // Override artboard dimensions to fill a dynamic container r.artboardWidth = container.clientWidth; r.artboardHeight = container.clientHeight; // Reset to intrinsic artboard size r.resetArtboardSize(); ``` ### Bounds Reads the artboard bounds as laid out by Rive. ### Usage ```typescript console.log("Bounds:", r.bounds); // { minX, minY, maxX, maxY } ``` ``` -------------------------------- ### Handle HiDPI / Retina displays Source: https://context7.com/rive-app/rive-wasm/llms.txt This method reads `window.devicePixelRatio`, scales the canvas drawing surface dimensions accordingly, and redraws the animation. It should be called on load and on window resize to maintain sharpness on high-resolution screens. ```APIDOC ## `rive.resizeDrawingSurfaceToCanvas()` — Handle HiDPI / Retina displays ### Description Reads `window.devicePixelRatio`, multiplies the canvas drawing surface dimensions by it, and redraws. Should be called after `onLoad` and on `window.resize` to keep the animation sharp on HiDPI screens. ### Usage ```typescript const r = new Rive({ src: "/logo.riv", canvas: document.getElementById("c") as HTMLCanvasElement, autoplay: true, onLoad: () => r.resizeDrawingSurfaceToCanvas(), }); // Keep crisp on resize and DPR changes (e.g. moving between monitors) window.addEventListener("resize", () => r.resizeDrawingSurfaceToCanvas()); window.matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`) .addEventListener("change", () => r.resizeDrawingSurfaceToCanvas()); // Use a custom DPR (e.g. cap at 2 for performance): r.resizeDrawingSurfaceToCanvas(Math.min(window.devicePixelRatio, 2)); ``` ``` -------------------------------- ### Control nested artboard inputs by path Source: https://context7.com/rive-app/rive-wasm/llms.txt These methods allow you to control inputs on state machines within nested artboards by providing a path-separated string, simplifying interaction with complex artboard compositions. ```APIDOC ## `rive.setBooleanStateAtPath()` / `rive.setNumberStateAtPath()` / `rive.fireStateAtPath()` — Control nested artboard inputs by path ### Description Sets inputs on state machines inside nested artboards (artboard composition) by providing the artboard hierarchy path as a `/`-separated string. This avoids needing to traverse the artboard tree manually. ### Usage ```typescript const r = new Rive({ src: "/dashboard.riv", canvas: document.getElementById("c") as HTMLCanvasElement, stateMachines: ["MainStateMachine"], autoplay: true, onLoad: () => r.resizeDrawingSurfaceToCanvas(), }); // Flip a boolean on a nested artboard named "Panel" r.setBooleanStateAtPath("isActive", true, "Panel"); // Set a number two levels deep: Panel → Gauge r.setNumberStateAtPath("fillPercent", 0.75, "Panel/Gauge"); // Fire a trigger on a nested artboard r.fireStateAtPath("reset", "Panel/Gauge"); ``` ``` -------------------------------- ### Subscribe to runtime events Source: https://context7.com/rive-app/rive-wasm/llms.txt These methods allow you to subscribe and unsubscribe callbacks for any `EventType`, including custom events fired from state machines. Multiple callbacks per event are supported. ```APIDOC ## `rive.on()` / `rive.off()` / `rive.removeAllRiveEventListeners()` — Subscribe to runtime events ### Description Subscribes or unsubscribes callbacks for any `EventType`. Multiple callbacks per event are supported. Subscribing to `EventType.RiveEvent` catches custom events fired from state machines at design time (e.g. `OpenUrlEvent` or general `RiveEvent`). ### Usage ```typescript import { Rive, EventType, RiveEventType } from "@rive-app/canvas"; const r = new Rive({ src: "/interactive.riv", canvas, stateMachines: "Main", autoplay: true }); const onStateChange = (e: Event) => { const states = e.data as string[]; console.log("States changed:", states); }; const onRiveEvent = (e: Event) => { const payload = e.data as any; if (payload.type === RiveEventType.OpenUrl) { console.log("Open URL:", payload.url, "target:", payload.target); // Prevent default behavior and handle manually: window.open(payload.url, payload.target ?? "_blank"); } else { // General event with design-time name and custom properties console.log("Rive event:", payload.name, payload.properties); } }; r.on(EventType.StateChange, onStateChange); r.on(EventType.RiveEvent, onRiveEvent); // Unsubscribe a specific callback r.off(EventType.StateChange, onStateChange); // Remove all listeners for one event type r.removeAllRiveEventListeners(EventType.RiveEvent); // Remove all listeners entirely r.removeAllRiveEventListeners(); ``` ``` -------------------------------- ### Handle HiDPI / Retina Displays Source: https://context7.com/rive-app/rive-wasm/llms.txt Call `resizeDrawingSurfaceToCanvas()` after `onLoad` and on `window.resize` to ensure animations remain sharp on HiDPI screens by scaling the drawing surface by `window.devicePixelRatio`. Optionally, a custom DPR can be provided to cap the scaling. ```typescript const r = new Rive({ src: "/logo.riv", canvas: document.getElementById("c") as HTMLCanvasElement, autoplay: true, onLoad: () => r.resizeDrawingSurfaceToCanvas(), }); // Keep crisp on resize and DPR changes (e.g. moving between monitors) window.addEventListener("resize", () => r.resizeDrawingSurfaceToCanvas()); window.matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`) .addEventListener("change", () => r.resizeDrawingSurfaceToCanvas()); // Use a custom DPR (e.g. cap at 2 for performance): r.resizeDrawingSurfaceToCanvas(Math.min(window.devicePixelRatio, 2)); ``` -------------------------------- ### Re-initialize with rive.reset() Source: https://context7.com/rive-app/rive-wasm/llms.txt Re-instantiates the artboard, animations, and state machines from the already-loaded file. All animation state is reset to initial values, useful for replay scenarios. ```typescript const r = new Rive({ src: "/game-over.riv", canvas: document.getElementById("c") as HTMLCanvasElement, stateMachines: "GameOver", autoplay: true, }); document.getElementById("replay")!.onclick = () => { r.reset({ stateMachines: "GameOver", autoplay: true, }); }; ``` -------------------------------- ### Configure Artboard Fit and Alignment with Layout Source: https://context7.com/rive-app/rive-wasm/llms.txt The `Layout` class controls how the Rive artboard is scaled and positioned within the canvas. Use `Fit` and `Alignment` enums to define scaling behavior and positioning. `Layout` instances are immutable; use `copyWith()` to create modified versions. ```typescript import { Layout, Fit, Alignment } from "@rive-app/canvas"; // Full-bleed cover layout const coverLayout = new Layout({ fit: Fit.Cover, alignment: Alignment.Center }); // Fixed viewport bounds (useful when canvas is larger than the artboard region) const boundedLayout = new Layout({ fit: Fit.Contain, alignment: Alignment.TopLeft, minX: 0, minY: 0, maxX: 800, maxY: 600, }); // Rive-driven responsive layout — artboard size follows canvas size const responsiveLayout = new Layout({ fit: Fit.Layout, alignment: Alignment.Center, layoutScaleFactor: 1, // multiply artboard logical pixels by this factor }); // Swap layout on an existing Rive instance const r = new Rive({ src: "/hero.riv", canvas, layout: coverLayout, autoplay: true }); // Update to a new layout without recreating the instance: r.layout = coverLayout.copyWith({ fit: Fit.Contain, alignment: Alignment.BottomCenter }); ``` -------------------------------- ### RuntimeLoader.setWasmUrl() / RuntimeLoader.setWasmBinary() — Custom WASM loading Source: https://context7.com/rive-app/rive-wasm/llms.txt The `RuntimeLoader` singleton manages fetching and initializing the WASM module. This section explains how to override the WASM URL, supply the binary directly, or configure the fallback URL. ```APIDOC ## RuntimeLoader.setWasmUrl() / RuntimeLoader.setWasmBinary() — Custom WASM loading ### Description The `RuntimeLoader` singleton manages fetching and initializing the WASM module. Override the WASM URL (e.g. for self-hosting or a specific CDN), supply the binary directly as an `ArrayBuffer` (e.g. bundled via a build tool), or configure the fallback URL for browsers that need the compatibility build. ### Usage Examples ```typescript import { RuntimeLoader, Rive } from "@rive-app/canvas"; // Option A: point to a self-hosted WASM file RuntimeLoader.setWasmUrl("/static/rive.wasm"); // Option B: disable the fallback entirely RuntimeLoader.setWasmFallbackUrl(null); // Option C: inline the WASM binary (e.g. bundled as a base64 data URL or fetched ahead of time) const wasmRes = await fetch("/static/rive.wasm"); RuntimeLoader.setWasmBinary(await wasmRes.arrayBuffer()); // Option D: await the runtime directly for advanced use const runtime = await RuntimeLoader.awaitInstance(); console.log("WASM runtime ready:", typeof runtime.makeRenderer); // After configuring the loader, construct Rive as normal const r = new Rive({ src: "/anim.riv", canvas: document.getElementById("c") as HTMLCanvasElement, autoplay: true, }); ``` ``` -------------------------------- ### Loading: rive.load() Source: https://context7.com/rive-app/rive-wasm/llms.txt Hot-swap the Rive file currently being used. This stops all current animations and loads a new Rive file while preserving event listeners and the canvas/renderer. ```APIDOC ## Loading: rive.load(params: RiveLoadParameters) ### Description Stops all current animations and loads a new Rive file while preserving all event listeners and the canvas/renderer. Useful for navigating between screens without creating a new `Rive` instance. ### Method `load(params: RiveLoadParameters)` ### Parameters - **params** (RiveLoadParameters): An object containing parameters for the new Rive file. - **src** (string): The URL or path to the new Rive file. - **animations** (string | string[]): Optional. The name(s) of animations to play initially. - **stateMachines** (string | string[]): Optional. The name(s) of state machines to play initially. - **autoplay** (boolean): Optional. Whether to autoplay animations/state machines after loading. ### Request Example ```typescript const r = new Rive({ src: "/screen-a.riv", canvas: document.getElementById("c") as HTMLCanvasElement, stateMachines: "Flow", autoplay: true, }); document.getElementById("next-screen")!.onclick = () => { r.load({ src: "/screen-b.riv", stateMachines: "Flow", autoplay: true, }); }; ``` ### Response No explicit response data is returned, but the Rive instance is updated with the new file. ``` -------------------------------- ### new Layout(params: LayoutParameters) Source: https://context7.com/rive-app/rive-wasm/llms.txt Controls the fit and alignment of the artboard within the canvas. It describes how the Rive artboard is scaled and positioned. Layout instances are immutable and can be modified using the `copyWith()` method. ```APIDOC ## new Layout(params: LayoutParameters) ### Description Controls the fit and alignment of the artboard within the canvas. It describes how the Rive artboard is scaled and positioned. Layout instances are immutable and can be modified using the `copyWith()` method. ### Method ```typescript new Layout(params: LayoutParameters) ``` ### Parameters #### `params` (LayoutParameters) - **fit** (Fit) - Describes how the artboard is scaled (e.g., `Fit.Contain`, `Fit.Cover`, `Fit.Fill`, `Fit.ScaleDown`, `Fit.Layout`). - **alignment** (Alignment) - Describes how the artboard is aligned within the canvas (e.g., `Alignment.Center`, `Alignment.TopLeft`). - **minX** (number) - Optional minimum X boundary for the layout. - **minY** (number) - Optional minimum Y boundary for the layout. - **maxX** (number) - Optional maximum X boundary for the layout. - **maxY** (number) - Optional maximum Y boundary for the layout. - **layoutScaleFactor** (number) - Multiplies artboard logical pixels by this factor when `fit` is `Fit.Layout`. ### Request Example ```typescript import { Layout, Fit, Alignment } from "@rive-app/canvas"; // Full-bleed cover layout const coverLayout = new Layout({ fit: Fit.Cover, alignment: Alignment.Center }); // Fixed viewport bounds (useful when canvas is larger than the artboard region) const boundedLayout = new Layout({ fit: Fit.Contain, alignment: Alignment.TopLeft, minX: 0, minY: 0, maxX: 800, maxY: 600, }); // Rive-driven responsive layout — artboard size follows canvas size const responsiveLayout = new Layout({ fit: Fit.Layout, alignment: Alignment.Center, layoutScaleFactor: 1, // multiply artboard logical pixels by this factor }); // Swap layout on an existing Rive instance const r = new Rive({ src: "/hero.riv", canvas, layout: coverLayout, autoplay: true }); // Update to a new layout without recreating the instance: r.layout = coverLayout.copyWith({ fit: Fit.Contain, alignment: Alignment.BottomCenter }); ``` ``` -------------------------------- ### Custom Asset Loading: assetLoader Callback Source: https://context7.com/rive-app/rive-wasm/llms.txt Allows interception of asset loading (images, fonts, audio) for custom handling. You can supply your own asset bytes or let Rive handle it via CDN or embedded assets. ```APIDOC ## `assetLoader` callback — Custom out-of-band asset loading Intercepts every asset (image, font, audio) that the Rive file references during load. Return `true` to signal that your code will supply the asset bytes; return `false` to let Rive handle it (CDN or embedded). Assets must be decoded via `decodeImage()`, `decodeFont()`, or `decodeAudio()` before being assigned, and `.unref()` must be called afterward to avoid memory leaks. ```typescript import { Rive, Fit, Alignment, Layout, FileAsset, ImageAsset, FontAsset, AudioAsset, decodeImage, decodeFont, decodeAudio, } from "@rive-app/canvas"; const r = new Rive({ src: "/rich-media.riv", canvas: document.getElementById("c") as HTMLCanvasElement, autoplay: true, layout: new Layout({ fit: Fit.Contain, alignment: Alignment.Center }), assetLoader: async (asset: FileAsset, bytes: Uint8Array) => { // If asset is already embedded (bytes provided) or hosted on Rive CDN, skip if (bytes.length > 0 || asset.cdnUuid.length > 0) return false; if (asset.isImage) { const res = await fetch("https://example.com/my-image.png"); const img = await decodeImage(new Uint8Array(await res.arrayBuffer())); (asset as ImageAsset).setRenderImage(img); img.unref(); // IMPORTANT: release after handing to asset return true; } if (asset.isFont) { const res = await fetch("https://cdn.example.com/Roboto.ttf"); const font = await decodeFont(new Uint8Array(await res.arrayBuffer())); (asset as FontAsset).setFont(font); font.unref(); return true; } if (asset.isAudio) { const res = await fetch(`/audio/${asset.uniqueFilename}`); const audio = await decodeAudio(new Uint8Array(await res.arrayBuffer())); (asset as AudioAsset).setAudioSource(audio); audio.unref(); return true; } return false; // Let runtime handle everything else }, }); ``` ``` -------------------------------- ### Resetting: rive.reset() Source: https://context7.com/rive-app/rive-wasm/llms.txt Re-initialize the current Rive file from scratch. This re-instantiates the artboard, animations, and state machines, resetting all animation state to initial values. ```APIDOC ## Resetting: rive.reset(params?: RiveResetParameters) ### Description Re-instantiates the artboard, animations, and state machines from the already-loaded file. All animation state is reset to initial values, which is useful for replay scenarios. ### Method `reset(params?: RiveResetParameters)` ### Parameters - **params** (RiveResetParameters): Optional. An object containing parameters to re-initialize with. - **animations** (string | string[]): Optional. The name(s) of animations to play after reset. - **stateMachines** (string | string[]): Optional. The name(s) of state machines to play after reset. - **autoplay** (boolean): Optional. Whether to autoplay animations/state machines after reset. ### Request Example ```typescript const r = new Rive({ src: "/game-over.riv", canvas: document.getElementById("c") as HTMLCanvasElement, stateMachines: "GameOver", autoplay: true, }); document.getElementById("replay")!.onclick = () => { r.reset({ stateMachines: "GameOver", autoplay: true, }); }; ``` ### Response No explicit response data is returned, but the Rive instance is reset to its initial state. ``` -------------------------------- ### FPS Monitoring: enableFPSCounter() / disableFPSCounter() Source: https://context7.com/rive-app/rive-wasm/llms.txt Enables or disables an FPS counter for performance monitoring. Can display a simple overlay or report values to a callback function. ```APIDOC ## `rive.enableFPSCounter()` / `rive.disableFPSCounter()` — FPS monitoring Enables an FPS counter. Without a callback, Rive appends a fixed-position `
` to the page showing the live frame rate. With a callback, the FPS value is delivered to the function on each animation frame. ```typescript const r = new Rive({ src: "/perf-test.riv", canvas, autoplay: true }); // Simple overlay (no callback): r.enableFPSCounter(); // Custom callback: const fpsDisplay = document.getElementById("fps-display")!; r.enableFPSCounter((fps: number) => { fpsDisplay.textContent = `${fps} FPS`; }); // Stop reporting: r.disableFPSCounter(); ``` ``` -------------------------------- ### Configure Local Rive File Source: https://github.com/rive-app/rive-wasm/blob/master/js/examples/_frameworks/vite_canvas_centered/README.md To use a local Rive file instead of the CDN default, place your .riv file in the public directory and update the RIVE_FILE_URL constant in main.ts. ```typescript const RIVE_FILE_URL = "/sample.riv"; ``` -------------------------------- ### Custom Asset Loading Source: https://context7.com/rive-app/rive-wasm/llms.txt Implement the `assetLoader` callback to intercept and provide custom bytes for assets like images, fonts, or audio. Return `true` if you supply the asset; return `false` to let Rive handle it. Ensure assets are decoded and `unref()` is called to prevent memory leaks. ```typescript import { Rive, Fit, Alignment, Layout, FileAsset, ImageAsset, FontAsset, AudioAsset, decodeImage, decodeFont, decodeAudio, } from "@rive-app/canvas"; const r = new Rive({ src: "/rich-media.riv", canvas: document.getElementById("c") as HTMLCanvasElement, autoplay: true, layout: new Layout({ fit: Fit.Contain, alignment: Alignment.Center }), assetLoader: async (asset: FileAsset, bytes: Uint8Array) => { // If asset is already embedded (bytes provided) or hosted on Rive CDN, skip if (bytes.length > 0 || asset.cdnUuid.length > 0) return false; if (asset.isImage) { const res = await fetch("https://example.com/my-image.png"); const img = await decodeImage(new Uint8Array(await res.arrayBuffer())); (asset as ImageAsset).setRenderImage(img); img.unref(); // IMPORTANT: release after handing to asset return true; } if (asset.isFont) { const res = await fetch("https://cdn.example.com/Roboto.ttf"); const font = await decodeFont(new Uint8Array(await res.arrayBuffer())); (asset as FontAsset).setFont(font); font.unref(); return true; } if (asset.isAudio) { const res = await fetch(`/audio/${asset.uniqueFilename}`); const audio = await decodeAudio(new Uint8Array(await res.arrayBuffer())); (asset as AudioAsset).setAudioSource(audio); audio.unref(); return true; } return false; // Let runtime handle everything else }, }); ``` -------------------------------- ### Interact with State Machine Inputs using rive.stateMachineInputs() Source: https://context7.com/rive-app/rive-wasm/llms.txt Read and write state machine inputs at runtime. Each input exposes a `.value` setter (for Number and Boolean) and a `.fire()` method (for Trigger). ```typescript const r = new Rive({ src: "/button.riv", canvas: document.getElementById("c") as HTMLCanvasElement, stateMachines: "ButtonSM", autoplay: true, onLoad: () => { const inputs = r.stateMachineInputs("ButtonSM"); // inputs: StateMachineInput[] — inspect types: inputs.forEach(i => console.log(i.name, i.type)); // e.g. "isHovered" Boolean, "clickCount" Number, "onClick" Trigger const isHovered = inputs.find(i => i.name === "isHovered"); const clickCount = inputs.find(i => i.name === "clickCount"); const onClick = inputs.find(i => i.name === "onClick"); document.getElementById("c")!.addEventListener("pointerenter", () => { if (isHovered) isHovered.value = true; }); document.getElementById("c")!.addEventListener("pointerleave", () => { if (isHovered) isHovered.value = false; }); document.getElementById("c")!.addEventListener("click", () => { if (clickCount) clickCount.value = (clickCount.value as number) + 1; onClick?.fire(); }); }, }); ``` -------------------------------- ### Control Rive Properties: volume, artboardWidth, artboardHeight Source: https://context7.com/rive-app/rive-wasm/llms.txt Modify runtime properties like `r.volume` for audio control (0-1) and `r.artboardWidth`/`r.artboardHeight` to override intrinsic artboard dimensions for responsive layouts. Use `r.resetArtboardSize()` to revert to the original dimensions. The `r.bounds` property provides the current layout dimensions. ```typescript const r = new Rive({ src: "/interactive-scene.riv", canvas: document.getElementById("c") as HTMLCanvasElement, stateMachines: "Scene", autoplay: true, onLoad: () => { // Mute audio r.volume = 0; // Restore to half volume on first click document.addEventListener("click", () => { r.volume = 0.5; }, { once: true }); // Override artboard dimensions to fill a dynamic container const container = document.getElementById("container")!; r.artboardWidth = container.clientWidth; r.artboardHeight = container.clientHeight; // Check the artboard bounds as laid out by Rive console.log("Bounds:", r.bounds); // { minX, minY, maxX, maxY } // Reset to intrinsic artboard size r.resetArtboardSize(); }, }); ``` -------------------------------- ### Canvas Layout Styling Source: https://github.com/rive-app/rive-wasm/blob/master/js/examples/_frameworks/out_of_band_example/index.html Basic CSS for centering canvas elements and adjusting layout for larger screens. ```css body { display: flex; flex-wrap: wrap; justify-content: center; align-items: center; margin: 0; height: 100vh; background: #f0f0f0; } canvas { margin: 10px; } /* Media query for screens wider than 1600px + 800px + 20px margin */ @media (min-width: 2420px) { body { flex-direction: row; /* Lays out children horizontally */ } } ``` -------------------------------- ### Enable/Disable FPS Counter Source: https://context7.com/rive-app/rive-wasm/llms.txt Use `enableFPSCounter()` to show live frame rate. Provide a callback for custom display or omit for a default overlay. Call `disableFPSCounter()` to stop reporting. ```typescript const r = new Rive({ src: "/perf-test.riv", canvas, autoplay: true }); // Simple overlay (no callback): r.enableFPSCounter(); // Custom callback: const fpsDisplay = document.getElementById("fps-display")!; r.enableFPSCounter((fps: number) => { fpsDisplay.textContent = `${fps} FPS`; }); // Stop reporting: r.disableFPSCounter(); ``` -------------------------------- ### Control Rive Animations with play(), pause(), and stop() Source: https://context7.com/rive-app/rive-wasm/llms.txt Control playback of named animations or state machines. Calling without arguments affects all instances. Queued safely before the file finishes loading. ```typescript const r = new Rive({ src: "/character.riv", canvas: document.getElementById("c") as HTMLCanvasElement, animations: ["idle", "walk"], // start with two linear animations autoplay: false, }); r.on(EventType.Load, () => { console.log("isPlaying:", r.isPlaying); // false — autoplay was false console.log("isPaused:", r.isPaused); // true r.play("walk"); // play only "walk" r.pause("idle"); // pause "idle" (already paused) r.stop("walk"); // stop and remove "walk" instance r.play(); // play everything remaining r.stop(); // stop all console.log("playingAnimations:", r.playingAnimationNames); console.log("pausedStateMachines:", r.pausedStateMachineNames); }); ``` -------------------------------- ### Read and write top-level text runs Source: https://context7.com/rive-app/rive-wasm/llms.txt These methods allow you to query and mutate named `TextValueRun` nodes directly on the active artboard. Ensure text run nodes are renamed in the Rive editor for runtime accessibility. ```APIDOC ## `rive.getTextRunValue()` / `rive.setTextRunValue()` — Read and write top-level text runs ### Description Queries or mutates a named `TextValueRun` node on the active artboard. Text run nodes must be renamed in the Rive editor for them to be queryable at runtime. ### Usage ```typescript const r = new Rive({ src: "/ui.riv", canvas: document.getElementById("c") as HTMLCanvasElement, autoplay: true, onLoad: () => { // Read current value const current = r.getTextRunValue("scoreLabel"); console.log("Score label:", current); // e.g. "0" // Update score display r.setTextRunValue("scoreLabel", "1,250"); r.setTextRunValue("playerName", "Alex"); }, }); ``` ``` -------------------------------- ### Hot-swap Rive Files with rive.load() Source: https://context7.com/rive-app/rive-wasm/llms.txt Stops all current animations and loads a new Rive file, preserving event listeners and the canvas/renderer. Useful for navigating between screens without creating a new Rive instance. ```typescript const r = new Rive({ src: "/screen-a.riv", canvas: document.getElementById("c") as HTMLCanvasElement, stateMachines: "Flow", autoplay: true, }); document.getElementById("next-screen")!.onclick = () => { r.load({ src: "/screen-b.riv", stateMachines: "Flow", autoplay: true, }); }; ``` -------------------------------- ### State Machine Inputs: rive.stateMachineInputs() Source: https://context7.com/rive-app/rive-wasm/llms.txt Read and write state machine inputs. This method returns an array of `StateMachineInput` objects for a running state machine, allowing runtime control over transitions. ```APIDOC ## State Machine Inputs: rive.stateMachineInputs(name) ### Description Returns an array of `StateMachineInput` objects for a running state machine. Each input exposes a `.value` setter (for `Number` and `Boolean` types) and a `.fire()` method (for `Trigger` types), allowing runtime-driven transitions. ### Method `stateMachineInputs(name: string): StateMachineInput[]` ### Parameters - **name** (string): The name of the state machine to get inputs from. ### Response - **StateMachineInput[]**: An array of `StateMachineInput` objects. - **name** (string): The name of the input. - **type** (string): The type of the input (e.g., "Boolean", "Number", "Trigger"). - **value** (any): The current value of the input (writable for Boolean and Number types). - **fire()**: A method to trigger the input (for Trigger types). ### Request Example ```typescript const r = new Rive({ src: "/button.riv", canvas: document.getElementById("c") as HTMLCanvasElement, stateMachines: "ButtonSM", autoplay: true, onLoad: () => { const inputs = r.stateMachineInputs("ButtonSM"); const isHovered = inputs.find(i => i.name === "isHovered"); const onClick = inputs.find(i => i.name === "onClick"); document.getElementById("c")!.addEventListener("pointerenter", () => { if (isHovered) isHovered.value = true; }); document.getElementById("c")!.addEventListener("pointerleave", () => { if (isHovered) isHovered.value = false; }); document.getElementById("c")!.addEventListener("click", () => { onClick?.fire(); }); }, }); ``` ``` -------------------------------- ### Build Rive WASM and JS APIs Source: https://github.com/rive-app/rive-wasm/blob/master/CONTRIBUTING.md Command to build the WASM and JavaScript APIs for the Rive runtime. This process compiles the WASM module and bundles the JavaScript code for both high-level and low-level APIs. ```sh ./build.sh ``` -------------------------------- ### Control Nested Artboard Inputs by Path Source: https://context7.com/rive-app/rive-wasm/llms.txt Use these functions to set boolean, number, or fire triggers on inputs within nested artboards by specifying the artboard hierarchy path. This simplifies interaction with complex artboard compositions. ```typescript const r = new Rive({ src: "/dashboard.riv", canvas: document.getElementById("c") as HTMLCanvasElement, stateMachines: ["MainStateMachine"], autoplay: true, onLoad: () => r.resizeDrawingSurfaceToCanvas(), }); // Flip a boolean on a nested artboard named "Panel" r.setBooleanStateAtPath("isActive", true, "Panel"); // Set a number two levels deep: Panel → Gauge r.setNumberStateAtPath("fillPercent", 0.75, "Panel/Gauge"); // Fire a trigger on a nested artboard r.fireStateAtPath("reset", "Panel/Gauge"); ``` -------------------------------- ### Commit Message: Documentation Change Source: https://github.com/rive-app/rive-wasm/blob/master/CONTRIBUTING.md Use this format for commit messages when only documentation is changed. ```git git commit -m "Docs: Adding a new link for another example page" ``` -------------------------------- ### Playback Control: rive.play(), rive.pause(), rive.stop() Source: https://context7.com/rive-app/rive-wasm/llms.txt Control the playback of named animations or state machines. Calling these methods without arguments affects all active animations/machines. These operations are safely queued before the file finishes loading. ```APIDOC ## Playback Control: rive.play(), rive.pause(), rive.stop() ### Description Start, pause, or stop named animations or state machines. Calling without arguments affects all instanced animations/machines. Queued safely before the file finishes loading. ### Method `play(animationNames?: string | string[])` `pause(animationNames?: string | string[])` `stop(animationNames?: string | string[])` ### Parameters - **animationNames** (string | string[]): Optional. The name(s) of the animation(s) or state machine(s) to control. If omitted, all active animations/machines are affected. ### Request Example ```typescript const r = new Rive({ src: "/character.riv", canvas: document.getElementById("c") as HTMLCanvasElement, animations: ["idle", "walk"], autoplay: false, }); r.on(EventType.Load, () => { r.play("walk"); r.pause("idle"); r.stop("walk"); r.play(); r.stop(); }); ``` ### Response No explicit response data is returned, but the playback state of animations/state machines is updated. ```