
Rive
- 1 installs
- 2 repo stars
- Updated August 3, 2026
- fandhe-ai/agent-reference-skills
Reference the Rive web animation runtimes (canvas, webgl2, react) for loading .riv files, state machines, data binding, ViewModels, events, and layout.
About
A structured reference for the Rive animation runtime covering the Rive class, React hooks, state machines, data binding/ViewModels, events, and layout across canvas and webgl2 packages. A frontend developer loads it when integrating Rive animations.
- Covers useRive, useStateMachineInput, and RiveComponent
- Data binding with ViewModel and ViewModelInstance
Rive by the numbers
- 1 all-time installs (skills.sh)
- Ranked #1,366 of 1,879 Documentation skills by installs in the Skillselion catalog
- Data as of Aug 3, 2026 (Skillselion catalog sync)
npx skills add https://github.com/fandhe-ai/agent-reference-skills --skill riveAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 1 |
|---|---|
| repo stars | ★ 2 |
| Last updated | August 3, 2026 |
| Repository | fandhe-ai/agent-reference-skills ↗ |
What it does
Reference the Rive web animation runtimes (canvas, webgl2, react) for loading .riv files, state machines, data binding, ViewModels, events, and layout.
Files
ディレクトリ構成
skills/rive/
SKILL.md
references/
runtimes-web/
README.md
packages.md
rive-constructor.md
rive-methods.md
layout.md
state-machine-playback.md
data-binding.md
loading-assets.md
fonts.md
audio.md
events.md
rive-file.md
preloading-wasm.md
runtimes-react/
README.md
overview.md
use-rive.md
use-state-machine-input.md
layout.md
data-binding.md
concepts/
README.md
state-machine.md
states.md
transitions.md
layers.md
inputs.md
listeners.md
data-binding.md
view-models.md
instances.md
properties.md
converters.md
enums.md
events.md
layout.md
samples/
README.md
web-basic.md
react-interactive.md
state-machine-control.md
scripts/
README.md
install.md探索手順
タスクからカテゴリを引き、カテゴリの README.md で目的のページを特定する:
1. 下記マッピング表でタスクに対応するカテゴリを探す 2. そのカテゴリの README.md を参照して目的のページを特定する 3. 該当ページの .md を Read して詳細を確認する
タスク → カテゴリ マッピング
| タスク | カテゴリ | 参照 README |
|---|---|---|
| パッケージ選定(canvas / webgl2 / canvas-lite)を知りたい | runtimes-web | references/runtimes-web/README.md |
| Rive コンストラクタのオプションを調べたい | runtimes-web | references/runtimes-web/README.md |
| play / pause / stop など Rive インスタンスメソッドを使いたい | runtimes-web | references/runtimes-web/README.md |
| .riv ファイルを複数インスタンスで共有したい(RiveFile) | runtimes-web | references/runtimes-web/README.md |
| フォント・音声アセットを動的に読み込みたい | runtimes-web | references/runtimes-web/README.md |
| WASM を自己ホストしてスタートアップを高速化したい | runtimes-web | references/runtimes-web/README.md |
| React で useRive を使ってアニメーションを表示したい | runtimes-react | references/runtimes-react/README.md |
| useStateMachineInput で State Machine 入力を操作したい | runtimes-react | references/runtimes-react/README.md |
| React で Data Binding / ViewModel を使いたい | runtimes-react | references/runtimes-react/README.md |
| State Machine の仕組み・状態・遷移を理解したい | concepts | references/concepts/README.md |
| Inputs / Listeners / Events の概念を把握したい | concepts | references/concepts/README.md |
| ViewModel / ViewModelInstance / Properties を理解したい | concepts | references/concepts/README.md |
| Converters / Enums / Data Binding の概念を調べたい | concepts | references/concepts/README.md |
| Layout / Fit / Alignment の概念を知りたい | concepts | references/concepts/README.md |
| 典型的な使い方を知りたい | samples | samples/README.md |
| インストール・パッケージ追加コマンドを知りたい | scripts | scripts/README.md |
Converters
Transformation nodes that modify a ViewModel property value before it is applied to a binding target. Converters adapt data to match the type or range expected by a scene element, and can be chained sequentially.
Signature / Usage
Converters are configured in the editor when setting up a binding or a "View Model Change" listener action. No runtime code is required — converters run automatically as part of the data binding pipeline.
ViewModel Property → [Converter A] → [Converter B] → Scene PropertyOptions / Props
String Converters
| Converter | Description |
|---|---|
| Pad | Pads a string to a fixed length |
| Trim | Removes leading/trailing whitespace |
| Convert to String | Converts a non-string value to its string representation |
| Remove Trailing Zeros | Strips insignificant trailing zeros from a numeric string |
Number Converters
| Converter | Description |
|---|---|
| Round | Rounds to a specified number of decimal places |
| Calculate | Applies a simple arithmetic operation |
| Range Map | Maps a value from one numeric range to another |
| Interpolator | Smooths changes over time |
| Formula | Evaluates a custom formula expression |
| Convert to Number | Converts a non-number value to a number |
Boolean Converters
| Converter | Description |
|---|---|
| Toggle | Inverts a boolean value |
List Converters
| Converter | Description |
|---|---|
| Number to List | Maps a number to a list index |
| List to Length | Returns the length of a list |
Color Converters
| Converter | Description |
|---|---|
| Interpolator | Smoothly interpolates between two colors over time |
Custom
| Converter | Description |
|---|---|
| Converter Script | Scripted custom transformation logic |
Notes
- Multiple converters can be chained in sequence; the output of each feeds into the input of the next.
- Many converter properties (e.g., a Range Map's maximum value, a Formula's multiplier) are themselves bindable to ViewModel properties, enabling dynamic behavior.
- The "System Enum to Uint" converter is applied automatically when binding an Enum property to a numeric scene property.
Related
- Data Binding
- Properties
- Enums
Data Binding
The system that connects data stored in ViewModels to properties in a Rive scene. When data changes, the scene updates automatically; changes in the scene can optionally write back to the data source.
Signature / Usage
Data binding is configured in the editor and consumed at runtime via the ViewModel instance API.
// Runtime: get ViewModel instance and read/write properties
const vmi = riveInstance.viewModelInstance;
// Number
const hp = vmi.number("health");
hp.value = 80;
// String
const label = vmi.string("playerName");
label.value = "Ada";
// Boolean
const active = vmi.boolean("isActive");
active.value = true;
// Trigger
const hit = vmi.trigger("onHit");
hit.trigger();
// Observe changes driven by the state machine
hp.on((event) => console.log("health changed:", event.data));Options / Props
| Bind Direction | Description |
|---|---|
| Source to Target (default) | ViewModel property drives the scene element |
| Target to Source | Scene element changes push back to the ViewModel property |
| Bidirectional | Both directions active simultaneously |
| Bind Once | Value applied once at startup; subsequent changes ignored |
Notes
- Binding is established in the editor: right-click a property → "Data Bind" → select ViewModel property. A green highlight indicates a valid binding; yellow indicates a type mismatch.
- Binding decouples data from scene hierarchy: reorganizing elements or renaming properties in the editor does not require runtime code changes.
- Data can be updated from the editor, runtime code, state machines, or scripting.
- The
Pathbinding option selects which specific nested ViewModel instance binds when ViewModels are hierarchically composed. - Property observers (
.on()) fire after state machine advances apply the change, not immediately on assignment.
Related
- View Models
- Instances
- Properties
- Converters
- Enums
Enums
Data types that restrict a ViewModel property to a predefined set of named options. Enums prevent invalid values and make designer intent explicit when a property should only hold a fixed set of states (e.g., game modes, layout variants, animation states).
Signature / Usage
Enums are defined in the Data panel and used as ViewModel property types. At runtime they are accessed via the ViewModel Instance API.
const vmi = riveInstance.viewModelInstance;
const mode = vmi.enum("gameMode");
console.log(mode.value); // e.g., "easy"
mode.value = "hard";Options / Props
| Kind | Description |
|---|---|
| System Enums | Built-in editor enums (e.g., Horizontal Align) provided by Rive |
| Custom Enums | User-defined sets created in the Data panel |
Creating a Custom Enum (editor)
1. Open the Data panel → click + → select Enum. 2. Add named options. 3. Add an Enum property to a ViewModel and select the custom enum type. 4. Set the default value in the right sidebar.
Notes
- Enum values are referenced by their string name at runtime.
- When binding an Enum property to a numeric scene property, the "System Enum to Uint converter" is applied automatically.
- Enums control Solo visibility: map each enum value to a corresponding Solo to switch between component variants; a "Convert to Number" converter is required in this case.
- Enums provide stronger type safety than raw strings or numbers for fixed-option properties.
Related
- Properties
- Data Binding
- Converters
Events
Signals emitted from within a Rive artboard to notify the runtime that something has happened. Events originate from timelines, states, transitions, or listeners and are consumed via runtime callbacks or ViewModel property observers.
Signature / Usage
// Playback lifecycle callbacks (provided in Rive constructor)
const r = new Rive({
src: "animation.riv",
onPlay: (event) => console.log("playing:", event.data), // string[]
onPause: (event) => console.log("paused:", event.data), // string[]
onStop: (event) => console.log("stopped:", event.data), // string[]
onLoop: (event) => console.log("looped:", event.data), // LoopEvent
onStateChange: (event) => console.log("state:", event.data), // string[]
});
// Alternative: subscribe after construction
r.on(EventType.StateChange, (event) => {
console.log("new state(s):", event.data); // string[] of state names
});
// Rive custom events (Report Event) via ViewModel property observers
const prop = vmi.boolean("wasTriggered");
prop.on((event) => console.log("custom event data:", event.data));Options / Props
Playback Lifecycle Callbacks
| Callback | event.data Type | Description |
|---|---|---|
onPlay | string[] | Fires when one or more animations/state machines start playing; data is their names |
onPause | string[] | Fires when one or more animations/state machines pause |
onStop | string[] | Fires when one or more animations/state machines stop |
onLoop | LoopEvent | Fires each time an animation completes a loop cycle; LoopEvent has animation: string and type: LoopType |
onStateChange | string[] | Fires when the active state changes in a state machine layer; data is the new state name(s) |
Rive Event Types (editor-defined)
| Type | Description |
|---|---|
| Open URL Event | Launches a URL in the browser at runtime |
| Audio Event | Triggers audio playback |
| General Event | Deprecated; previously used for custom runtime communication |
Signaling Events (editor)
| Source | Method |
|---|---|
| Timeline | Use "Report Event" in the Inspector to fire at a specific frame |
| State | Click + next to Events in the state; choose start or end |
| Transition | Click + next to Events in the transition; choose start or end |
| Listener | Click + below the State Machine graph → "Report Event" |
Notes
onStateChangedelivers the string name(s) of the newly active states; use these to react to state machine transitions in application logic.- Custom events (Report Event) fired from Rive are now consumed via ViewModel property observers (
.on()) rather than a dedicated event API, because the general "Rive Events" system is deprecated in favor of Data Binding. onLoopLoopTypevalues:OneShot,Loop,PingPong.- All callbacks can also be registered/deregistered dynamically using
riveInstance.on(EventType, callback)andriveInstance.off(EventType, callback).
Related
- State Machine
- Listeners
- Data Binding
Inputs
Named values attached to a State Machine that drive transition conditions and blend parameters. Inputs are the primary mechanism for controlling a state machine from runtime code or listeners.
Signature / Usage
Inputs are defined in the State Machine panel and referenced by name in transition conditions. At runtime they are accessed via the stateMachineInputs() API (legacy) or Data Binding (recommended).
// Legacy API (deprecated — prefer Data Binding)
const inputs = riveInstance.stateMachineInputs("State Machine 1");
const hover = inputs.find(i => i.name === "isHovered"); // Boolean
const speed = inputs.find(i => i.name === "speed"); // Number
const clicked = inputs.find(i => i.name === "onClick"); // Trigger
hover.value = true; // set boolean
speed.value = 0.8; // set number
clicked.fire(); // fire triggerOptions / Props
| Type | value | Description |
|---|---|---|
| Boolean | true / false | Binary flag; transitions conditioned on true/false equality |
| Number | number | Numeric value; transitions conditioned on =, >, < comparisons; also used to drive 1D Blend States |
| Trigger | — | Momentary signal; set to true for one frame then auto-resets; use .fire() to activate |
Notes
- Inputs are referenced by name (string); names must match exactly between editor and runtime code.
- The
StateMachineInputobject exposes:.name(string),.value(number | boolean, read/write),.type(StateMachineInputType enum),.fire()(trigger only). - Direct input mutation is deprecated as of the Data Binding era. The recommended approach is to bind inputs to ViewModel properties and update the ViewModel at runtime instead.
- Triggers automatically reset after one state machine advance frame; they do not need to be manually reset to false.
Related
- State Machine
- Transitions
- Data Binding
Instances
ViewModel Instances are the concrete data containers created from a ViewModel blueprint. Each instance holds its own independent set of property values and can be bound to an artboard or component.
Signature / Usage
// Three factory methods on a ViewModel
const vm = riveInstance.viewModel("Player");
const blank = vm.instance(); // all properties at type defaults
const fallback = vm.defaultInstance(); // the instance marked default in the editor
const byName = vm.instanceByName("Player 1"); // lookup by name set in editorNotes
- Multiple instances can exist for the same ViewModel simultaneously, each with independent values.
- The active instance on a Rive object is accessible via
riveInstance.viewModelInstance. - Instances can be swapped at runtime to change the data set driving an artboard.
- To manage instances in the editor: select a ViewModel → click the Controls icon → use
+/-to add or remove, double-click to rename, click an instance to edit its property values. - Instances marked as "exported" are bundled inside the
.rivfile; unmark to reduce file size when the instance is only needed during design.
Related
- View Models
- Data Binding
- Properties
Layers
Independent parallel animation tracks within a single State Machine. Each layer runs its own graph of states and transitions, allowing multiple animations to play simultaneously on the same artboard.
Signature / Usage
Layers appear as tabs in the Layers panel of the State Machine editor. Each layer has its own Entry, Exit, and Any states.
State Machine
├── Layer 1 (leftmost) — lower priority
│ └── [states & transitions]
├── Layer 2
│ └── [states & transitions]
└── Layer N (rightmost) — highest priorityNotes
- Each layer plays one animation at a time, but multiple layers run concurrently, enabling animation blending.
- When layers control the same object properties, the rightmost layer takes priority.
- Use layers to separate concerns: e.g., a background animation in Layer 1, character interaction logic in Layer 2.
- Managing layers:
- Add: click
+in the Layers tab - Reorder: drag and drop
- Right-click options: Delete, Duplicate, Disable/Enable
- The Exit State in a layer stops only that layer; other layers continue running.
Related
- State Machine
- States
Layout
The Layout configuration controls how a Rive artboard is scaled and positioned within its host container. It defines the Fit mode (scaling strategy) and Alignment (anchor position), and optionally constrains the drawing region.
Signature / Usage
import { Rive, Layout, Fit, Alignment } from "@rive-app/canvas";
const r = new Rive({
src: "animation.riv",
canvas: document.getElementById("canvas"),
layout: new Layout({
fit: Fit.Contain, // default
alignment: Alignment.Center, // default
layoutScaleFactor: 1, // optional scale multiplier (used with Fit.Layout)
minX: 0, // optional bounds for partial rendering
minY: 0,
maxX: 0,
maxY: 0,
}),
autoplay: true,
});
// Update layout responsively
window.addEventListener("resize", () => {
r.layout = new Layout({ fit: Fit.Cover, alignment: Alignment.TopCenter });
r.resizeDrawingSurfaceToCanvas();
});Options / Props
Fit Modes
| Value | Description |
|---|---|
Fit.Contain | (default) Preserves aspect ratio; scales so the artboard's larger dimension fills its container dimension |
Fit.Cover | Preserves aspect ratio; scales so the artboard's smaller dimension fills its container dimension (may clip) |
Fit.Fill | Stretches to fill the container; aspect ratio not preserved |
Fit.FitWidth | Preserves aspect ratio; scales artboard width to match container width |
Fit.FitHeight | Preserves aspect ratio; scales artboard height to match container height |
Fit.None | No scaling; artboard renders at its original design size (may clip or leave space) |
Fit.ScaleDown | Like Contain, but only scales down — never scales up beyond original size |
Fit.Layout | Uses the Rive layout engine for responsive artboard layout; artboard dimensions match the container |
Alignment Options
| Value | Description |
|---|---|
Alignment.TopLeft | Anchor top-left |
Alignment.TopCenter | Anchor top-center |
Alignment.TopRight | Anchor top-right |
Alignment.CenterLeft | Anchor center-left |
Alignment.Center | (default) Anchor center |
Alignment.CenterRight | Anchor center-right |
Alignment.BottomLeft | Anchor bottom-left |
Alignment.BottomCenter | Anchor bottom-center |
Alignment.BottomRight | Anchor bottom-right |
Layout Class Constructor
| Parameter | Type | Description |
|---|---|---|
fit | Fit | Scaling strategy |
alignment | Alignment | Anchor position within the container |
layoutScaleFactor | number | Scale multiplier applied when using Fit.Layout |
minX, minY | number | Top-left corner of optional drawing bounds |
maxX, maxY | number | Bottom-right corner of optional drawing bounds |
Notes
- Alignment has no effect for
Fit.FillandFit.Layout, since those modes expand the artboard to match the container exactly. - For responsive layouts: set
fittoFit.Layout, configure artboard constraints in the editor, then callresizeDrawingSurfaceToCanvas()on window resize events (and on device pixel ratio changes). - The
layoutproperty on a live Rive instance is a getter/setter — assign a newLayoutobject to update it without recreating the instance. - Layout in the editor (Row/Column-based positioning of child objects) is a separate concept from the runtime
Layoutclass described here; the editor layout system controls intra-artboard element positioning.
Related
- State Machine
Listeners
State Machine components that respond to user interactions (pointer events) or internal changes (ViewModel property changes, component events) and translate them into actions — updating data, firing events, or repositioning objects — without requiring runtime code.
Signature / Usage
A listener is configured entirely in the editor. Each listener has three parts: a Target, a Condition, and one or more Actions.
Listener
├── Target — shape/group acting as a hit area, or an Artboard/Component
├── Condition — what triggers the listener
└── Action(s) — what happens when triggeredOptions / Props
Target
| Option | Description |
|---|---|
| Shape / Group | Functions as a hitbox for pointer events |
| Artboard / Component | Used for listening to forwarded events from nested components |
Condition
| Condition | Description |
|---|---|
| Pointer Down | Fires when pointer is pressed on target |
| Pointer Up | Fires when pointer is released on target |
| Pointer Enter | Fires when pointer enters target bounds |
| Pointer Exit | Fires when pointer leaves target bounds |
| Pointer Move | Fires on every pointer movement over target |
| Click | Fires on a full click (down + up) on target |
| Listen for Event | Fires when a specified event is received from an Artboard/Component target |
| View Model Property Change | Fires when a selected ViewModel property changes value |
Action
| Action | Description |
|---|---|
| View Model Change | Sets a ViewModel property to a specific value or to the value of another property |
| Report Event | Fires a named Rive event |
| Align Target | Moves an object to follow the pointer; preserves original offset if configured |
Notes
- Opaque Target: When disabled, pointer events pass through the hit area and can trigger multiple overlapping listeners simultaneously.
- Converters can be applied to "View Model Change" actions when mapping one property to another (e.g., incrementing a number).
- Listeners enable fully designer-authored interactivity without any runtime code for common pointer interactions.
Related
- State Machine
- Inputs
- Data Binding
- Events
Properties
Individual data fields within a ViewModel. Each property has a name, a type, and a value. Properties are bound to scene elements in the editor and read/written at runtime through the ViewModel Instance API.
Signature / Usage
const vmi = riveInstance.viewModelInstance;
// Number
const score = vmi.number("score");
score.value = 42;
// String
const name = vmi.string("userName");
name.value = "Ada";
// Boolean
const visible = vmi.boolean("isVisible");
visible.value = false;
// Color (RGBA hex string or numeric encoding depending on runtime)
const tint = vmi.color("primaryColor");
// Enum
const mode = vmi.enum("gameMode");
mode.value = "hard";
// Observe a property change (fires after state machine advance)
score.on((event) => console.log(event.data));
score.off(); // remove all observersOptions / Props
| Type | Bound to editor elements | Notes |
|---|---|---|
| Number | Numeric properties (position, opacity, speed, …) | Used in 1D Blend conditions and transition conditions |
| String | Text content, asset paths | |
| Boolean | Visibility toggles, binary flags | |
| Color | Fill color, stroke color (RGBA) | |
| Enum | Solo selection, mode variants | Requires system or custom enum definition |
| List | Repeating components (inventory items, players, …) | Contains nested ViewModel instances |
Notes
- Properties are created in the Data panel; add via "Add View Model Property" and choose the type.
- Property names are strings and must match exactly in runtime code.
- A property can be bound in multiple directions: Source→Target (ViewModel drives scene), Target→Source (scene drives ViewModel), or Bidirectional.
- The "Bind Once" flag applies the value only at startup and ignores subsequent changes — useful for static initialization.
- Observers (
.on()) fire after state machine advances propagate changes, not immediately on.valueassignment.
Related
- View Models
- Data Binding
- Converters
- Enums
concepts
| Name | Description | Path |
|---|---|---|
| State Machine | Visual framework for connecting animations and defining interactive transition logic | state-machine.md |
| States | Nodes in the State Machine graph: Entry, Exit, Any, Single Animation, 1D Blend, and Additive Blend | states.md |
| Transitions | Directed connections between states; define conditions and timing for state changes | transitions.md |
| Layers | Independent parallel animation tracks within a State Machine; enable concurrent animation blending | layers.md |
| Inputs | Named Boolean, Number, or Trigger values that drive State Machine transition conditions | inputs.md |
| Listeners | Pointer/event handlers that update data or fire events without runtime code | listeners.md |
| Data Binding | System that connects ViewModel properties to scene elements; drives automatic scene updates | data-binding.md |
| ViewModels | Reusable data blueprints defining property structure; ViewModel Instances hold actual values | view-models.md |
| Instances | ViewModel Instances — concrete data containers created from a ViewModel blueprint | instances.md |
| Properties | Individual typed data fields within a ViewModel (Number, String, Boolean, Color, Enum, List) | properties.md |
| Converters | Transformation nodes that modify property values before they are applied to binding targets | converters.md |
| Enums | Fixed-set data types restricting a property to a predefined set of named options | enums.md |
| Events | Signals emitted from artboards; includes lifecycle callbacks (onPlay, onPause, onLoop, onStop, onStateChange) and custom events | events.md |
| Layout | Controls how an artboard is scaled (Fit) and positioned (Alignment) within its host container | layout.md |
State Machine
A visual framework for connecting animations and defining interactive transition logic within a Rive artboard. Every artboard includes one default state machine; additional state machines can be created as needed.
Signature / Usage
The State Machine replaces the timeline when selected in the editor. It consists of a graph workspace where states and transitions are arranged to define how animations flow in response to inputs and events.
Artboard
└── State Machine
├── Layers (one or more)
│ ├── Entry State → (transition) → Animation State
│ ├── Animation State(s)
│ ├── Any State
│ └── Exit State
├── Inputs (Boolean / Number / Trigger)
└── ListenersOptions / Props
| Component | Description |
|---|---|
| Entry State | Starting point of a state machine layer; first state played on load |
| Exit State | Signals the layer to stop playing; useful with multiple layers |
| Any State | Transitions connected to it can activate from any current state |
| Animation States | Single, 1D Blend, or Additive Blend states containing timeline animations |
| Inputs | Named values (Boolean, Number, Trigger) that drive transition conditions |
| Layers | Independent parallel animation tracks within one state machine |
| Listeners | Pointer/event handlers that update inputs or fire events at runtime |
Notes
- Each state machine layer plays one animation at a time.
- Multiple layers can run concurrently to blend animations; rightmost layer takes priority when properties conflict.
- State machines are the recommended mechanism for interactivity — direct animation playback control at runtime is deprecated in favor of state machines driven by Data Binding.
Related
- States
- Transitions
- Layers
- Inputs
- Listeners
States
Nodes in the State Machine graph that represent distinct animation conditions. Each state holds a timeline animation (or blend of animations) that plays while the state is active.
Signature / Usage
States appear as nodes on the State Machine graph. They are connected by transitions and activated according to input conditions.
State Machine Layer
├── Entry State (auto-included)
├── Exit State (auto-included)
├── Any State (auto-included)
└── [User States]
├── Single Animation State
├── 1D Blend State
└── Additive Blend StateOptions / Props
| Type | Description |
|---|---|
| Entry State | The starting point of a layer; the animation attached here plays first |
| Exit State | Stops the layer; useful when coordinating multiple layers |
| Any State | Connected states can be reached from any current state regardless of normal transition logic |
| Single Animation State | Plays one timeline; can be one-shot, looping, or ping-pong |
| 1D Blend State | Blends two or more timelines using a single Number input; animations ramp additively as the value changes |
| Additive Blend State | Blends multiple timelines using multiple Number inputs; useful for complex outcomes like facial expressions |
Notes
- State properties include: animation selection, playback speed (positive = forward, negative = reverse), and transitions.
- Actions can be triggered at the start or end of a state (e.g., set a property, fire an event).
- 1D Blend States are commonly used for things like health bars and loading indicators.
- Additive Blend States support "by value" (baseline, uncontrolled) and "by property" (controlled via Number inputs) blending modes.
Related
- State Machine
- Transitions
- Inputs
Transitions
Directed connections between states in the State Machine graph that define when and how the machine moves from one state to another.
Signature / Usage
Create a transition by hovering over the edge of a state until an ellipse appears, then dragging to the destination state. Multiple transitions between the same states create "or" (any-match) logic; multiple conditions on one transition create "and" (all-match) logic.
State A --[condition(s)]--> State BOptions / Props
| Property | Description |
|---|---|
| Duration | Time (ms) for the cross-fade blend between states; 0 = instant snap |
| Exit Time | Optional: time or percentage into the source animation before the transition can fire; 100% waits for animation completion |
| Pause When Exiting | Pauses the outgoing animation during the transition, preventing overlap |
| Interpolation | Blend curve: Linear, Cubic, or Hold |
| Conditions | Rules that must be satisfied for the transition to fire (Boolean, Number, Trigger, or Script) |
| Actions | Operations that run at transition start or end (set property, report event, align target, control focus, run script) |
Notes
- Condition types:
- Boolean — fires when a named input equals true or false
- Number — fires when a named input satisfies an equality or comparison (=, >, <)
- Trigger — fires once when the named trigger input is activated
- Custom Script — complex conditions via scripting API
- Multiple transitions from the same source state act as an "or": whichever condition is satisfied first wins.
- Longer durations create smoother blending between state animations.
- Actions on a transition can be set to run at transition start or completion.
Related
- State Machine
- States
- Inputs
ViewModels
Reusable data blueprints that define the structure of data used in a Rive scene. A ViewModel defines which properties exist and their types; ViewModel Instances hold the actual values.
Signature / Usage
ViewModels are created in the Data panel. At runtime, instances are obtained from the Rive instance.
// Retrieve a ViewModel and create an instance
const viewModel = riveInstance.viewModel("Car");
const vmiBlank = viewModel.instance(); // blank instance (default values)
const vmiDefault = viewModel.defaultInstance(); // instance marked as default in editor
const vmiNamed = viewModel.instanceByName("Race1"); // named instanceOptions / Props
ViewModel Properties
| Type | Description |
|---|---|
| Number | Numeric value (float) |
| String | Text value |
| Boolean | True / false flag |
| Color | RGBA color value |
| Enum | Fixed-set selection from a custom or system enum |
| List | Collection of ViewModel instances, used for repeating content |
Connection Patterns
| Pattern | Description |
|---|---|
| Top-Level Instance | Data lives on the main artboard; accessible throughout the file and all nested components |
| Nested Component Instance | Parent ViewModel references child instances; useful for collections |
| Stateful Components | Self-contained components that manage their own data without requiring a parent reference |
Notes
- A ViewModel itself stores no values — it is a schema. Instances store values.
- When a ViewModel is created, Rive automatically generates one instance named "Instance" for immediate editor testing.
- Multiple instances can share the same ViewModel structure while holding independent data.
- By default, instances are exported inside
.rivfiles. Disable export for development-only instances to keep file sizes small. - ViewModels support nested composition: a ViewModel property can reference another ViewModel, enabling parent–child data hierarchies.
Related
- Data Binding
- Instances
- Properties
Data Binding
Connects React application state to Rive animated elements through View Models and View Model Instances. Replaces the deprecated useStateMachineInput pattern.
Signature / Usage
import { useRive, useViewModel, useViewModelInstance, useViewModelInstanceBoolean } from '@rive-app/react-webgl2';
export default function Example() {
const { rive, RiveComponent } = useRive({
src: 'your_file.riv',
autoBind: true,
});
const viewModel = useViewModel(rive);
const instance = useViewModelInstance(viewModel, { useDefault: true, rive });
const { value: isActive, setValue: setIsActive } =
useViewModelInstanceBoolean('isToggleOn', instance);
return (
<>
<RiveComponent />
<button onClick={() => setIsActive(!isActive)}>Toggle</button>
</>
);
}Options / Props
useViewModel
useViewModel(rive: Rive | null, options?: { name?: string; index?: number }): ViewModel | null| Option | Type | Description |
|---|---|---|
name | string | Select a View Model by name |
index | number | Select a View Model by index |
| _(no option)_ | — | Returns the artboard's default View Model |
useViewModelInstance
useViewModelInstance(viewModel: ViewModel | null, options?: UseViewModelInstanceOptions): ViewModelInstance | null| Option | Type | Description |
|---|---|---|
useDefault | boolean | Use the editor's "Default" named instance |
useNew | boolean | Create a new blank instance |
name | string | Select a named instance |
index | number | Select an instance by index |
rive | Rive | Automatically bind the instance to the Rive runtime |
Property hooks
All property hooks share the signature:
useViewModelInstance<Type>(propertyPath: string, instance: ViewModelInstance | null, options?): PropertyStateUse forward-slash-delimited paths for nested properties (e.g. 'settings/theme/name').
| Hook | Return members | Description |
|---|---|---|
useViewModelInstanceBoolean | value, setValue | Boolean property |
useViewModelInstanceNumber | value, setValue | Number property |
useViewModelInstanceString | value, setValue | String property |
useViewModelInstanceEnum | value, setValue, values | Enum property (string-typed; values lists all options) |
useViewModelInstanceColor | value, setValue, setRgb, setRgba, setAlpha, setOpacity | Color property |
useViewModelInstanceTrigger | trigger | Returns a function to fire the trigger; accepts { onTrigger } callback option |
useViewModelInstanceImage | setValue | Set an image from a decoded RiveImageAsset |
useViewModelInstanceList | length, addInstance, addInstanceAt, removeInstance, removeInstanceAt, getInstanceAt, swap | Dynamic list of View Model instances |
useViewModelInstanceArtboard | setValue | Swap an artboard reference at runtime |
Notes
- Hook values update automatically (triggering re-renders) when the Rive instance changes a bound property.
- For triggers, use the
onTriggercallback option rather than checking return values. - Properties require a state machine or artboard advance to apply changes to bound elements.
autoBind: trueinuseRiveis the preferred pattern when using the file's default View Model and instance; the bound instance is also accessible viarive?.viewModelInstance.- List properties can contain mixed View Model types in a single list.
- When setting image properties, always call
decodedImage.unref()after passing it tosetValueto avoid memory leaks.
Related
- useRive
- useStateMachineInput
Layout Props
Controls how a Rive artboard scales and positions itself within its container. Pass a Layout instance to the layout prop of the Rive component or the useRive hook.
Signature / Usage
new Layout(options?: LayoutOptions): Layoutimport Rive, { Layout, Fit, Alignment } from '@rive-app/react-webgl2';
export const Example = () => (
<Rive
src="https://cdn.rive.app/animations/vehicles.riv"
layout={new Layout({ fit: Fit.Contain, alignment: Alignment.TopCenter })}
/>
);// With useRive hook
import { useRive, Layout, Fit, Alignment } from '@rive-app/react-webgl2';
export default function Example() {
const { RiveComponent } = useRive({
src: 'my-file.riv',
layout: new Layout({
fit: Fit.Cover,
alignment: Alignment.TopCenter,
}),
autoplay: true,
});
return <RiveComponent />;
}Options / Props
LayoutOptions
| Name | Type | Default | Description |
|---|---|---|---|
fit | Fit | Fit.Contain | Scaling strategy (see Fit values below) |
alignment | Alignment | Alignment.Center | Position within the container when content doesn't fill it |
minX | number | — | Left bound of the rendering area (overrides alignment) |
minY | number | — | Top bound of the rendering area (overrides alignment) |
maxX | number | — | Right bound of the rendering area (overrides alignment) |
maxY | number | — | Bottom bound of the rendering area (overrides alignment) |
layoutScaleFactor | number | — | Multiplier for content scale when using Fit.Layout |
Fit Values
| Value | Description |
|---|---|
Fit.Layout | Uses the Rive layout engine to apply responsive layout, matching container dimensions |
Fit.Contain | Scales preserving aspect ratio; may leave empty space (default) |
Fit.Cover | Scales to fill container preserving aspect ratio; may clip content |
Fit.Fill | Stretches to fill without preserving aspect ratio |
Fit.FitWidth | Matches container width, preserves aspect ratio |
Fit.FitHeight | Matches container height, preserves aspect ratio |
Fit.ScaleDown | Like Contain, but only scales down (not up) |
Fit.None | No scaling; renders at original artboard dimensions |
Alignment Values
TopLeft, TopCenter, TopRight, CenterLeft, Center, CenterRight, BottomLeft, BottomCenter, BottomRight
Notes
Fit.Layoutautomatically responds to window resizing and device pixel ratio changes.- Providing
minX/minY/maxX/maxYoverrides thealignmentsetting. layoutScaleFactoris only meaningful whenfitisFit.Layout.
Related
- Overview
- useRive
React Runtime Overview
The Rive React runtime provides two primary packages for integrating Rive animations into React applications. Choose a package based on which rendering backend you need.
Signature / Usage
# Recommended — Rive Renderer with WebGL2
npm i --save @rive-app/react-webgl2
# Canvas-based alternative
npm i --save @rive-app/react-canvasimport Rive from '@rive-app/react-webgl2';
export const Simple = () => (
<Rive
src="https://cdn.rive.app/animations/vehicles.riv"
stateMachines="bumpy"
/>
);Options / Props
| Package | Renderer | Notes |
|---|---|---|
@rive-app/react-webgl2 | Rive Renderer (WebGL2) | Recommended; supports Vector Feathering and advanced features |
@rive-app/react-canvas | Canvas 2D | No Rive Renderer; broader browser compatibility |
@rive-app/react-canvas-lite | Canvas 2D (lite) | Smaller bundle; not recommended for files using Rive Text |
Notes
- The default export (
Rive) is a drop-in component for simple use cases; useuseRivefor advanced control. @rive-app/react-webgl2: enable the draftWEBGL_shader_pixel_local_storageChrome extension to get full performance benefits of the Rive Renderer. Browsers without it fall back to MSAA.- Rive does not instantiate until
<RiveComponent />is rendered — the underlying<canvas>must be present in the DOM. - The canvas initially defaults to 0×0; set sizing via
classNameor a wrapper container. - For conditional rendering, isolate
useRivein a dedicated wrapper component to prevent animation restarts during re-renders.
Related
- useRive Hook
- Layout Props
- Data Binding
runtimes-react
| Name | Description | Path |
|---|---|---|
| Overview | Package selection (@rive-app/react-webgl2 vs react-canvas), installation, basic component usage | overview.md |
| useRive | Primary hook for Rive instantiation; params, UseRiveOptions, and RiveState return values | use-rive.md |
| useStateMachineInput | Deprecated hook for reading and writing state machine inputs (boolean, number, trigger) | use-state-machine-input.md |
| Layout Props | Layout object, Fit enum, Alignment enum, and bounds configuration for canvas scaling | layout.md |
| Data Binding | ViewModel / ViewModelInstance hooks for connecting React state to Rive animations | data-binding.md |
useRive
Primary hook for accessing the Rive runtime with full control. Returns a RiveComponent for rendering and the underlying rive instance for imperative control.
Signature / Usage
useRive(riveParams: UseRiveParameters | null, opts?: UseRiveOptions): RiveStateimport { useRive } from '@rive-app/react-webgl2';
export default function Example() {
const { rive, RiveComponent } = useRive({
src: 'https://cdn.rive.app/animations/vehicles.riv',
stateMachines: 'bumpy',
autoplay: false,
});
return (
<RiveComponent
onMouseEnter={() => rive && rive.play()}
onMouseLeave={() => rive && rive.pause()}
/>
);
}Options / Props
UseRiveParameters (riveParams)
Passed directly to the underlying Rive web runtime object. Accepts null or undefined for deferred / conditional initialization.
| Name | Type | Default | Description |
|---|---|---|---|
src | string | — | URL or public path to the .riv file |
buffer | ArrayBuffer | — | Raw .riv bytes; alternative to src |
artboard | string | — | Name of the artboard to display (defaults to the editor default) |
animations | `string \ | string[]` | — |
stateMachines | `string \ | string[]` | — |
layout | Layout | — | Layout configuration (Fit, Alignment, bounds) |
autoplay | boolean | true | Start playback immediately after load |
autoBind | boolean | false | Auto-bind the default View Model instance on load |
onLoad | EventCallback | — | Fired after the Rive file loads (note: rive instance may not be available yet — prefer useEffect) |
UseRiveOptions (opts)
React-specific options passed as the second argument.
| Name | Type | Default | Description |
|---|---|---|---|
useDevicePixelRatio | boolean | true | Scales resolution to the device pixel ratio; requires setContainerRef to be wired |
fitCanvasToArtboardHeight | boolean | false | Resizes the canvas height to match the artboard height |
useOffscreenRenderer | boolean | true | Shares a single WebGL context across Rive instances to work around browser WebGL context limits |
RiveState (return value)
| Name | Type | Description |
|---|---|---|
rive | `Rive \ | null` |
RiveComponent | React.FC | JSX element that renders the canvas; pass className/style and event handlers |
canvas | `HTMLCanvasElement \ | null` |
container | `HTMLElement \ | null` |
setCanvasRef | React.RefCallback | Ref callback for manual canvas control |
setContainerRef | React.RefCallback | Ref callback for manual container control (required when useDevicePixelRatio is true) |
Notes
RiveComponentwraps the<canvas>inside a<div>.style/classNameprops target the<div>(layout); other attributes are forwarded to<canvas>.- Do not rely on
onLoadto access theriveinstance — useuseEffectwatchingriveinstead. - Rive will not instantiate until
<RiveComponent />is rendered; the canvas must be present in the DOM. - For conditional rendering patterns, lift
useRiveinto an isolated wrapper component to avoid animation restarts caused by parent re-renders.
Related
- Overview
- useStateMachineInput
- Layout Props
- Data Binding
useStateMachineInput
Hook to retrieve a named input from an active state machine, enabling boolean, number, and trigger interactions from React code.
Deprecated — For new projects, prefer Data Binding with useViewModelInstance* hooks.Signature / Usage
useStateMachineInput(
rive: Rive | null,
stateMachineName?: string,
inputName?: string,
initialValue?: number | boolean
): StateMachineInput | nullimport { useRive, useStateMachineInput } from '@rive-app/react-webgl2';
export default function Example() {
const { rive, RiveComponent } = useRive({
src: 'my-animation.riv',
stateMachines: 'State Machine 1',
autoplay: true,
});
const hoverInput = useStateMachineInput(rive, 'State Machine 1', 'isHovered');
const clickTrigger = useStateMachineInput(rive, 'State Machine 1', 'onClick');
return (
<RiveComponent
onMouseEnter={() => hoverInput && (hoverInput.value = true)}
onMouseLeave={() => hoverInput && (hoverInput.value = false)}
onClick={() => clickTrigger && clickTrigger.fire()}
/>
);
}Options / Props
Parameters
| Name | Type | Description |
|---|---|---|
rive | `Rive \ | null` |
stateMachineName | string | Name of the state machine containing the input |
inputName | string | Name of the input as defined in the Rive editor |
initialValue | `number \ | boolean` |
StateMachineInput (return value)
| Member | Type | Description |
|---|---|---|
name | string (getter) | The input's identifier |
value | `number \ | boolean` (getter/setter) |
fire() | () => void | Fire a trigger input |
Notes
- Returns
nulluntil theriveinstance is loaded and the state machine is active. - Use
fire()for trigger-type inputs; setvaluefor boolean or number inputs. useStateMachineInputis deprecated — new projects should use Data Binding hooks (useViewModelInstanceBoolean,useViewModelInstanceNumber,useViewModelInstanceTrigger, etc.).
Related
- useRive
- Data Binding
Audio
Playing audio from Rive animations in the web runtime.
Signature / Usage
import { Rive } from "@rive-app/webgl2";
const r = new Rive({
src: "scene.riv",
canvas: document.getElementById("canvas") as HTMLCanvasElement,
autoplay: true,
stateMachines: "Main",
});
// Adjust playback volume (0.0 = muted, 1.0 = full)
r.volume = 0.5;Options / Props
volume property
r.volume: number // getter / setter| Value | Effect |
|---|---|
1.0 | Full volume (default) |
0.0 | Muted |
0.5 | 50% of the audio event's default volume |
Acts as a multiplier applied on top of each audio event's own volume setting from the editor.
Audio asset loading
Embedded audio plays automatically with no extra setup. For referenced audio assets, provide an assetLoader callback and check asset.isAudio:
assetLoader: (asset, bytes) => {
if (asset.isAudio) {
// load and assign audio bytes
return true;
}
return false;
}Notes
- Most browsers block audio playback until the user interacts with the page (click or touch). Audio will not play before that first interaction regardless of Rive configuration.
- Audio requires
@rive-app/webgl2or@rive-app/canvas; it is not supported in@rive-app/canvas-lite. - Audio events are authored in the Rive editor and triggered via timelines, state transitions, or listeners.
Related
- loading-assets.md
- rive-constructor.md
- packages.md
Data Binding
Connect JavaScript code to animated properties through View Models and View Model Instances (VMI).
Signature / Usage
import { Rive } from "@rive-app/webgl2";
const r = new Rive({
src: "scene.riv",
canvas: document.getElementById("canvas") as HTMLCanvasElement,
autoplay: true,
autoBind: true, // auto-bind default ViewModel with default instance
stateMachines: "Main",
onLoad: () => {
const vmi = r.viewModelInstance;
// Read / write properties
vmi.boolean("isVisible").value = true;
vmi.string("label").value = "Hello, Rive!";
vmi.number("score").value = 42;
vmi.trigger("onClick").trigger();
// Observe changes
vmi.number("score").on((event) => {
console.log("score changed:", event.data);
});
},
});Options / Props
Getting View Models from a Rive instance
| Method | Signature | Description |
|---|---|---|
viewModelByName | (name: string) => ViewModel | Get View Model by name |
viewModelByIndex | (index: number) => ViewModel | Get View Model by index |
defaultViewModel | () => ViewModel | Get the file's default View Model |
viewModelCount | number | Total number of View Models |
Creating View Model Instances
| Method | Signature | Description |
|---|---|---|
vm.instance() | () => ViewModelInstance | Blank instance (all defaults: 0, "", false, …) |
vm.defaultInstance() | () => ViewModelInstance | Designer-designated primary instance |
vm.instanceByIndex | (index: number) => ViewModelInstance | Instance by index |
vm.instanceByName | (name: string) => ViewModelInstance | Instance by editor name |
vm.instanceCount | number | Total number of named instances |
Binding an instance
r.bindViewModelInstance(vmi); // manual binding (autoBind: false)
// or
const vmi = r.viewModelInstance; // read bound instance (autoBind: true)Property accessors on ViewModelInstance
| Accessor | Returns | Description |
|---|---|---|
vmi.boolean(name) | BooleanProperty | Boolean property |
vmi.string(name) | StringProperty | String property |
vmi.number(name) | NumberProperty | Floating-point property |
vmi.color(name) | ColorProperty | Color property |
vmi.trigger(name) | TriggerProperty | Trigger property |
vmi.enum(name) | EnumProperty | Enumeration property |
vmi.viewModel(name) | ViewModelInstance | Nested View Model |
vmi.list(name) | ListProperty | Dynamic list of VMIs |
vmi.image(name) | ImageProperty | Raster image property |
vmi.artboard(name) | ArtboardProperty | Artboard swap property |
ColorProperty helpers
const c = vmi.color("bgColor");
c.value = 0xFF000000; // ARGB integer
c.rgb(255, 0, 0); // RGB
c.rgba(255, 0, 0, 128); // RGB + alpha
c.argb(128, 255, 0, 0); // ARGB
c.opacity(0.5); // alpha onlyNested property path
// Chain
const n = vmi.viewModel("Card").number("rating");
// Path string (forward-slash delimited)
const n = vmi.number("Card/rating");Observability
const prop = vmi.number("score");
prop.on((event) => console.log(event.data)); // subscribe
prop.off(callback); // remove specific listener
prop.off(); // remove all listenersList property
const list = vmi.list("todos");
list.length; // number of items
list.addInstance(todoVMI); // append
list.removeInstance(todoVMI); // remove by reference
list.removeInstanceAt(0); // remove by index
list.swap(0, 1); // swap two itemsImage property
const img = vmi.image("avatar");
const decoded = await rive.decodeImage(new Uint8Array(await res.arrayBuffer()));
img.value = decoded;
decoded.unref(); // release after setting
img.value = null; // clearArtboard property (component swap)
const artboardProp = vmi.artboard("Character");
const assetsFile = new RiveFile({ src: "assets.riv", onLoad: () => {
artboardProp.value = assetsFile.getBindableArtboard("Hero");
}});
assetsFile.init();Notes
- Data Binding is the modern replacement for the legacy
stateMachineInputs()API. - Pass
autoBind: trueto automatically bind the default View Model with its default instance. - Nested View Models can be accessed via method chaining or forward-slash path strings.
- Always call
unref()on decoded image assets once assigned to free memory.
Related
- rive-constructor.md
- rive-methods.md
- state-machine-playback.md
- loading-assets.md
Events
Subscribe to Rive runtime lifecycle events and Rive-defined custom events from animations and state machines.
Signature / Usage
import { Rive, EventType, RiveEventType } from "@rive-app/webgl2";
const r = new Rive({
src: "scene.riv",
canvas: document.getElementById("canvas") as HTMLCanvasElement,
autoplay: true,
stateMachines: "Main",
});
// Subscribe to Rive events fired from the animation
r.on(EventType.RiveEvent, (event) => {
const riveEvent = event.data;
if (riveEvent.type === RiveEventType.OpenUrl) {
// Handle URL event manually
const anchor = document.createElement("a");
anchor.href = riveEvent.properties.url;
anchor.target = riveEvent.properties.target ?? "_blank";
if (anchor.href) anchor.click();
}
if (riveEvent.type === RiveEventType.General) {
console.log("General event:", riveEvent.name, riveEvent.properties);
}
});
// Subscribe to lifecycle events
r.on(EventType.StateChange, (event) => {
console.log("state changed to:", event.data);
});
// Unsubscribe
r.off(EventType.RiveEvent, myCallback);Options / Props
on / off
r.on(type: EventType, callback: (event: Event) => void): void
r.off(type: EventType, callback: (event: Event) => void): voidEventType enum
| Value | Fires when |
|---|---|
EventType.Load | .riv file finished loading |
EventType.LoadError | File load failed |
EventType.Play | Playback started or resumed |
EventType.Pause | Playback paused |
EventType.Stop | Playback stopped |
EventType.Loop | Timeline animation completed a loop |
EventType.StateChange | State machine transitioned to a new state |
EventType.RiveEvent | A Rive-defined event fired from animation/state machine |
EventType.Advance | Artboard advanced (fires every frame) |
RiveEventType enum (for EventType.RiveEvent payloads)
| Value | Description |
|---|---|
RiveEventType.General | Custom general event with arbitrary properties |
RiveEventType.OpenUrl | URL navigation event |
Event payload shape for EventType.RiveEvent
{
data: {
name: string; // event name from the editor
type: RiveEventType; // General or OpenUrl
properties: Record<string, unknown>; // custom key/value pairs
// OpenUrl-specific:
properties.url?: string;
properties.target?: string; // e.g. "_blank"
}
}Lifecycle event payload
// StateChange
{ data: string[] } // active state name(s)
// Play / Pause / Stop / Loop
{ data: string } // animation or state machine nameConstructor callback shortcuts
The following constructor parameters are shorthand for on() calls:
| Parameter | Equivalent |
|---|---|
onLoad | EventType.Load |
onLoadError | EventType.LoadError |
onPlay | EventType.Play |
onPause | EventType.Pause |
onStop | EventType.Stop |
onLoop | EventType.Loop |
onStateChange | EventType.StateChange |
onAdvance | EventType.Advance |
Notes
EventType.RiveEventreplaces the deprecated general Rive Events system; prefer Data Binding for state communication in new projects.OpenUrlevents do not navigate automatically; you must implement the navigation logic in the callback.- Setting
automaticallyHandleEvents: truein the constructor makes the runtime open URLs forOpenUrlevents without a manual callback. - General (deprecated) events still fire via
EventType.RiveEventwithtype === RiveEventType.General.
Related
- rive-constructor.md
- rive-methods.md
- state-machine-playback.md
- data-binding.md
Fonts
Dynamic font loading and fallback font configuration for the Rive web runtime.
Signature / Usage
import { RiveFont, decodeFont, Rive } from "@rive-app/webgl2";
// Set fallback font callback BEFORE creating Rive instance
RiveFont.setFallbackFontCallback((codePoint, weight) => {
// Return decoded font(s) for the given Unicode code point, or null
if (codePoint >= 0x0E00 && codePoint <= 0x0E7F) {
return [decodedThaiFont];
}
return null;
});
const r = new Rive({
src: "scene.riv",
canvas: document.getElementById("canvas") as HTMLCanvasElement,
autoplay: true,
assetLoader: async (asset, bytes) => {
if (asset.isFont) {
const res = await fetch("/fonts/custom.ttf");
const font = await decodeFont(new Uint8Array(await res.arrayBuffer()));
asset.setFont(font);
font.unref();
return true;
}
return false;
},
});Options / Props
Dynamic font loading via assetLoader
See loading-assets.md for the full assetLoader API. For fonts, the key steps are:
1. Fetch the font file as an ArrayBuffer 2. Decode with decodeFont(bytes: Uint8Array): Promise<Font> 3. Call asset.setFont(font) 4. Call font.unref() to release the reference
Fallback font API (v2.37.1+)
RiveFont.setFallbackFontCallback(
(codePoint: number, weight: number) => Font[] | null
)| Parameter | Type | Description |
|---|---|---|
codePoint | number | Unicode code point of the missing glyph |
weight | number | Font weight value requested |
Returns an array of decoded Font objects to attempt in order, or null to skip fallback.
Notes
- Browsers block access to system fonts for security; fallback fonts must be explicitly decoded and provided.
RiveFont.setFallbackFontCallbackmust be called before Rive initialization to take effect.- The fallback callback may be invoked multiple times per missing glyph if successive fallback fonts also lack support.
- Fonts embedded in the
.rivfile are loaded automatically with no extra code.
Related
- loading-assets.md
- rive-constructor.md
Layout / Fit / Alignment
Controls how Rive content is scaled and positioned within the canvas.
Signature / Usage
import { Rive, Layout, Fit, Alignment } from "@rive-app/webgl2";
const r = new Rive({
src: "vehicles.riv",
canvas: document.getElementById("canvas") as HTMLCanvasElement,
layout: new Layout({
fit: Fit.Cover,
alignment: Alignment.TopCenter,
}),
autoplay: true,
});Options / Props
Layout constructor
new Layout(params?: LayoutParameters)| Name | Type | Default | Description |
|---|---|---|---|
fit | Fit | Fit.Contain | How the artboard scales inside the canvas |
alignment | Alignment | Alignment.Center | Where the artboard is positioned when it doesn't fill the canvas |
minX | number | — | Override left bound (relative to canvas) |
minY | number | — | Override top bound |
maxX | number | — | Override right bound |
maxY | number | — | Override bottom bound |
Fit enum values
| Value | Description |
|---|---|
Fit.Layout | Apply the Rive layout engine; artboard fills container (artboard must use layouts) |
Fit.Contain | Preserve aspect ratio; scale so the larger dimension matches the container (default) |
Fit.Cover | Preserve aspect ratio; scale so the smaller dimension matches the container (may clip) |
Fit.Fill | Stretch to fill container; aspect ratio not preserved |
Fit.FitWidth | Scale to match container width; preserve aspect ratio |
Fit.FitHeight | Scale to match container height; preserve aspect ratio |
Fit.ScaleDown | Like Contain when artboard is larger than container; otherwise use original size |
Fit.None | Use original artboard dimensions; no scaling |
Alignment enum values
| Value | Description |
|---|---|
Alignment.TopLeft | Top-left corner |
Alignment.TopCenter | Top-center |
Alignment.TopRight | Top-right corner |
Alignment.CenterLeft | Middle-left |
Alignment.Center | Center (default) |
Alignment.CenterRight | Middle-right |
Alignment.BottomLeft | Bottom-left corner |
Alignment.BottomCenter | Bottom-center |
Alignment.BottomRight | Bottom-right corner |
Notes
Alignmenthas no effect whenfitisFit.Layout.- When providing explicit
minX/minY/maxX/maxYbounds, they override alignment positioning. - Call
r.resizeToCanvas()after canvas resize to update the layout bounds.
Related
- rive-constructor.md
- packages.md
Loading Assets
Three strategies for supplying image, font, and audio assets to a Rive file at runtime.
Signature / Usage
import { Rive, decodeFont, decodeImage } from "@rive-app/webgl2";
const r = new Rive({
src: "scene.riv",
canvas: document.getElementById("canvas") as HTMLCanvasElement,
autoplay: true,
assetLoader: async (asset, bytes) => {
if (asset.isFont) {
const response = await fetch("/fonts/custom.ttf");
const font = await decodeFont(new Uint8Array(await response.arrayBuffer()));
asset.setFont(font);
font.unref();
return true; // we handled it
}
if (asset.isImage) {
const response = await fetch("/images/hero.png");
const image = await decodeImage(new Uint8Array(await response.arrayBuffer()));
asset.setImage(image);
image.unref();
return true;
}
return false; // let runtime handle it
},
});Options / Props
Asset loading strategies
| Strategy | How | When to use |
|---|---|---|
| Embedded | Asset baked into the .riv binary | Simple setup; larger file |
| Hosted (CDN) | Asset stored on Rive's CDN; fetched automatically | Voyager/Enterprise plan; zero-config |
| Referenced | Asset excluded from binary; loaded via assetLoader | Minimal file size; dynamic asset selection |
assetLoader callback
assetLoader: (asset: FileAsset, bytes: Uint8Array) => booleanCalled for every asset the runtime detects in the .riv file on load.
| Parameter | Type | Description |
|---|---|---|
asset | FileAsset | Asset metadata and setter methods |
bytes | Uint8Array | Asset bytes when embedded; empty for referenced assets |
Return true if your code handled the asset; false to let the runtime handle it.
FileAsset properties and methods
| Member | Type | Description |
|---|---|---|
asset.name | string | Asset name as set in the editor |
asset.isFont | boolean | True for font assets |
asset.isImage | boolean | True for image assets |
asset.isAudio | boolean | True for audio assets |
asset.cdnUuid | string | CDN identifier (for hosted assets) |
asset.setFont(font) | (font: Font) => void | Assign a decoded font |
asset.setImage(image) | (image: Image) => void | Assign a decoded image |
Decode helpers
| Function | Description |
|---|---|
decodeFont(bytes: Uint8Array): Promise<Font> | Decode raw bytes into a Rive Font object |
decodeImage(bytes: Uint8Array): Promise<Image> | Decode raw bytes into a Rive Image object |
Supported image formats
JPEG, PNG, WebP.
Notes
- Always call
asset.unref()(orfont.unref()/image.unref()) after assigning the decoded asset to allow garbage collection. enableRiveAssetCDN: falsedisables automatic CDN fetching when you want full control over all asset loading.- For Data Binding image properties, use
decodeImageand assign viavmi.image("name").value = decoded— see data-binding.md.
Related
- rive-constructor.md
- fonts.md
- audio.md
- data-binding.md
Web Packages Overview
Three npm packages for different rendering needs and bundle-size trade-offs.
Signature / Usage
npm install @rive-app/webgl2
# or
npm install @rive-app/canvas
# or
npm install @rive-app/canvas-lite<!-- Via CDN (no bundler) -->
<script src="https://unpkg.com/@rive-app/webgl2"></script>import { Rive } from "@rive-app/webgl2";
// or selective import
import * as rive from "@rive-app/webgl2";Options / Props
| Package | Renderer | Text / Layout / Audio / Scripting | Bundle Size |
|---|---|---|---|
@rive-app/webgl2 | Rive Renderer (WebGL2) | Full support | Larger |
@rive-app/canvas | CanvasRenderingContext2D | Full support | Medium |
@rive-app/canvas-lite | CanvasRenderingContext2D | Not supported | Smallest |
Notes
@rive-app/webgl2is the recommended default — best rendering quality and performance for most use cases.- Choose
@rive-app/canvaswhen WebGL2 is unavailable or simpler graphics are targeted. - Choose
@rive-app/canvas-liteonly when bundle size is the top priority and text, layouts, audio, and scripting features are not needed. - When rendering many Rive instances on one page with WebGL2, set
useOffscreenRenderer: trueto avoid hitting the browser's WebGL context limit. - The legacy
@rive-app/webglpackage is deprecated (no updates after v2.37.0).
Related
- rive-constructor.md
- layout.md
Preloading WASM
Self-host and preload the Rive WebAssembly binary for faster startup and better reliability.
Signature / Usage
import riveWASMResource from "@rive-app/webgl2/rive.wasm";
import { Rive, RuntimeLoader } from "@rive-app/webgl2";
// Call before creating any Rive instance
RuntimeLoader.setWasmUrl(riveWASMResource);
const r = new Rive({
src: "scene.riv",
canvas: document.getElementById("canvas") as HTMLCanvasElement,
autoplay: true,
});Options / Props
RuntimeLoader.setWasmUrl(url: string): void
| Parameter | Type | Description |
|---|---|---|
url | string | Data URI or URL pointing to the .wasm binary |
RuntimeLoader is a singleton; call setWasmUrl once per page, before any Rive instance is created.
Notes
- By default the runtime fetches
rive.wasmfrom the Rive CDN on first use. - Preloading avoids the CDN dependency and speeds up time-to-first-frame.
- Your bundler (Vite, webpack, etc.) may require configuration to import
.wasmfiles as data URIs. - The WASM version must match the installed
@rive-app/*package version.
Related
- rive-constructor.md
- packages.md
runtimes-web
| Name | Description | Path |
|---|---|---|
| packages | Package selection: @rive-app/webgl2 vs canvas vs canvas-lite | packages.md |
| Rive (constructor) | RiveParameters — all constructor options including src, canvas, autoplay, autoBind, callbacks | rive-constructor.md |
| Rive instance methods | play/pause/stop/reset, resize, stateMachineInputs, on/off, cleanup | rive-methods.md |
| Layout / Fit / Alignment | Layout class, Fit enum (Contain/Cover/Fill/…), Alignment enum | layout.md |
| State Machine Playback | stateMachineInputs, StateMachineInput (boolean/number/trigger), onStateChange | state-machine-playback.md |
| Data Binding | ViewModel, ViewModelInstance, property accessors, lists, images, artboard swap, observability | data-binding.md |
| Loading Assets | assetLoader callback, embedded/hosted/referenced strategies, decodeFont, decodeImage | loading-assets.md |
| Fonts | Dynamic font loading, RiveFont.setFallbackFontCallback for missing glyphs | fonts.md |
| Audio | volume property, embedded vs referenced audio, browser autoplay restriction | audio.md |
| Events | EventType, RiveEventType, on/off API, RiveEvent payload, OpenUrl handling | events.md |
| RiveFile | Pre-parse and share a .riv file across multiple Rive instances | rive-file.md |
| Preloading WASM | RuntimeLoader.setWasmUrl — self-host the WASM binary for faster startup | preloading-wasm.md |
Rive (constructor)
High-level class that loads a .riv file, manages the render loop, and exposes playback controls.
Signature / Usage
const r = new Rive(params: RiveParameters): Riveimport { Rive } from "@rive-app/webgl2";
const r = new Rive({
src: "https://cdn.rive.app/animations/vehicles.riv",
canvas: document.getElementById("canvas") as HTMLCanvasElement,
autoplay: true,
stateMachines: "bumpy",
onLoad: () => {
r.resizeDrawingSurfaceToCanvas();
},
});Options / Props
File source (one required)
| Name | Type | Description |
|---|---|---|
src | string | URL or relative path to a .riv file |
buffer | ArrayBuffer | Raw bytes of a .riv file |
riveFile | RiveFile | Pre-parsed RiveFile instance (for sharing across instances) |
Rendering
| Name | Type | Default | Description |
|---|---|---|---|
canvas | `HTMLCanvasElement \ | OffscreenCanvas` | — |
layout | Layout | Fit.Contain / Alignment.Center | Fit and alignment configuration |
useOffscreenRenderer | boolean | false | Share a single WebGL2 context across many instances |
Playback
| Name | Type | Default | Description |
|---|---|---|---|
artboard | string | default artboard | Artboard name to render |
stateMachines | `string \ | string[]` | — |
autoplay | boolean | false | Start playback immediately after load |
autoBind | boolean | false | Auto-bind the default ViewModelInstance |
Asset loading
| Name | Type | Default | Description |
|---|---|---|---|
enableRiveAssetCDN | boolean | true | Allow runtime to fetch hosted assets from Rive's CDN |
assetLoader | (asset: FileAsset, bytes: Uint8Array) => boolean | — | Custom callback for referenced assets |
Interaction
| Name | Type | Default | Description |
|---|---|---|---|
enableMultiTouch | boolean | false | Support multiple simultaneous touch points |
automaticallyHandleEvents | boolean | false | Handle Rive events (e.g., OpenUrl) automatically |
dispatchPointerExit | boolean | true | Fire pointer-exit event when pointer leaves canvas |
tabIndex | number | — | Canvas tab index for keyboard focus |
Lifecycle callbacks
| Name | Type | Description |
|---|---|---|
onLoad | () => void | File loaded successfully |
onLoadError | () => void | File load failed |
onPlay | (event: Event) => void | Playback started |
onPause | (event: Event) => void | Playback paused |
onStop | (event: Event) => void | Playback stopped |
onLoop | (event: Event) => void | Timeline animation looped |
onStateChange | (event: Event) => void | State machine transitioned to a new state |
onAdvance | (event: Event) => void | Artboard advanced each frame |
Notes
- Call
r.resizeDrawingSurfaceToCanvas()insideonLoadto match the canvas's device pixel ratio. - Call
r.cleanup()when the instance is no longer needed to free WASM memory. - Only one artboard can be rendered per
Riveinstance.
Related
- packages.md
- layout.md
- state-machine-playback.md
- data-binding.md
- loading-assets.md
- rive-methods.md
RiveFile
Pre-parse a .riv file once and share it across multiple Rive instances to avoid redundant loading and parsing.
Signature / Usage
import { Rive, RiveFile } from "@rive-app/webgl2";
const file = new RiveFile({
src: "vehicles.riv",
onLoad: () => {
// File is parsed and ready — create instances
const r1 = new Rive({
riveFile: file,
canvas: document.getElementById("canvas1") as HTMLCanvasElement,
stateMachines: "Motion",
autoplay: true,
});
const r2 = new Rive({
riveFile: file,
canvas: document.getElementById("canvas2") as HTMLCanvasElement,
stateMachines: "Motion",
autoplay: true,
});
},
onLoadError: (err) => console.error(err),
});
file.init();Options / Props
RiveFile constructor
| Name | Type | Description |
|---|---|---|
src | string | URL or path to the .riv file |
buffer | ArrayBuffer | Raw bytes alternative to src |
onLoad | () => void | Called when the file is parsed and ready |
onLoadError | (err: unknown) => void | Called on load failure |
View Model access from RiveFile
| Method | Signature | Description |
|---|---|---|
viewModelByName | (name: string) => ViewModel | Get a View Model by name |
getBindableArtboard | (name: string) => Artboard | Get an artboard suitable for component swap |
Notes
file.init()must be called after constructingRiveFileto begin loading.- Each
Riveinstance receives independent playback state even when sharing the sameRiveFile. - Useful when the same
.rivfile is used in multiple locations on the same page (e.g., a list of animated cards).
Related
- rive-constructor.md
- data-binding.md
Rive Instance Methods
Methods available on a Rive instance for playback control, rendering, data access, and resource management.
Signature / Usage
const r = new Rive({ ... });
// Playback
r.play("animationName");
r.pause();
r.stop();
r.reset({ stateMachines: "Machine", autoplay: true });
// Rendering
r.resizeDrawingSurfaceToCanvas();
r.startRendering();
r.stopRendering();
// Cleanup
r.cleanup();Options / Props
Playback control
| Method | Signature | Description |
|---|---|---|
play | `(names?: string \ | string[], autoplay?: boolean) => void` |
pause | `(names?: string \ | string[]) => void` |
stop | `(names?: string \ | string[]) => void` |
reset | `(params?: { artboard?: string; stateMachines?: string \ | string[]; autoplay?: boolean }) => void` |
Rendering
| Method | Signature | Description |
|---|---|---|
resizeDrawingSurfaceToCanvas | (customDPR?: number) => void | Adjust canvas drawing surface for device pixel ratio |
resizeToCanvas | () => void | Update layout bounds to match canvas size |
startRendering | () => void | Begin the render loop |
stopRendering | () => void | Halt the render loop |
drawFrame | () => void | Render a single frame |
State machine inputs
| Method | Signature | Description |
|---|---|---|
stateMachineInputs | (name: string) => StateMachineInput[] | Return all inputs for a named state machine |
Data / state accessors
| Property / Method | Type | Description |
|---|---|---|
contents | RiveFile | Artboards, animations, and state machines in the file |
activeArtboard | string | Currently active artboard name |
playingAnimationNames | string[] | Names of currently playing timeline animations |
playingStateMachineNames | string[] | Names of currently playing state machines |
bounds | AABB | Axis-aligned bounding box of the artboard |
viewModelCount | number | Number of View Models in the file |
viewModelInstance | `ViewModelInstance \ | null` |
View Model
| Method | Signature | Description |
|---|---|---|
viewModelByName | (name: string) => ViewModel | Get a View Model by name |
viewModelByIndex | (index: number) => ViewModel | Get a View Model by index |
defaultViewModel | () => ViewModel | Get the file's default View Model |
bindViewModelInstance | (vmi: ViewModelInstance) => void | Manually bind a View Model instance |
enums | () => object | Return all enum definitions in the file |
Events
| Method | Signature | Description |
|---|---|---|
on | (type: EventType, callback: EventCallback) => void | Subscribe to a runtime event |
off | (type: EventType, callback: EventCallback) => void | Unsubscribe from a runtime event |
Cleanup
| Method | Signature | Description |
|---|---|---|
cleanup | () => void | Dispose all WASM resources (artboard, animations, renderer) |
cleanupInstances | () => void | Dispose artboard/animation instances only, keep file |
Notes
stateMachineInputs(name)is the legacy approach for controlling state machines; prefer Data Binding for new projects.reset()recreates instances from scratch; any bound ViewModelInstance must be rebound afterward.- Always call
cleanup()when removing a Rive component to prevent WASM memory leaks.
Related
- rive-constructor.md
- state-machine-playback.md
- data-binding.md
- events.md
State Machine Playback
Control state machine playback and interact with inputs (booleans, numbers, triggers) from JavaScript.
Signature / Usage
import { Rive, StateMachineInputType } from "@rive-app/webgl2";
const r = new Rive({
src: "interactive.riv",
canvas: document.getElementById("canvas") as HTMLCanvasElement,
autoplay: true,
stateMachines: "MainMachine",
onLoad: () => {
r.resizeDrawingSurfaceToCanvas();
const inputs = r.stateMachineInputs("MainMachine");
const boolInput = inputs.find((i) => i.name === "isHovered");
const numInput = inputs.find((i) => i.name === "progress");
const trigInput = inputs.find((i) => i.name === "clicked");
// Boolean
boolInput.value = true;
// Number
numInput.value = 0.75;
// Trigger
trigInput.fire();
},
onStateChange: (event) => {
console.log("current state(s):", event.data);
},
});Options / Props
Playback methods
| Method | Description |
|---|---|
r.play(name?) | Resume or start the state machine from its current position |
r.pause(name?) | Halt advancement; preserve current frame |
r.stop(name?) | Stop and reset to the entry state |
r.reset(params?) | Dispose and recreate instances (optionally change artboard/state machine) |
stateMachineInputs(name: string): StateMachineInput[]
Returns an array of input objects for the named state machine.
StateMachineInput
| Member | Type | Description |
|---|---|---|
name | string | Input name as set in the Rive editor |
type | StateMachineInputType | Number (56), Trigger (58), or Boolean (59) |
value | `boolean \ | number` |
fire() | () => void | Fire a trigger input (sets it true for one frame) |
StateMachineInputType enum
| Constant | Value | Description |
|---|---|---|
StateMachineInputType.Number | 56 | Floating-point number |
StateMachineInputType.Trigger | 58 | One-shot trigger |
StateMachineInputType.Boolean | 59 | Boolean flag |
onStateChange callback
Fires whenever the state machine transitions to a new state.
onStateChange: (event: { data: string[] }) => voidevent.data contains the name(s) of the current active state(s).
Notes
- The
stateMachineInputs()approach is the legacy way of controlling state machines; for new projects, prefer Data Binding. - State machines may "settle" (stop advancing) when no further state changes will occur — this is a performance optimization.
- Multiple state machine names can be passed to the constructor:
stateMachines: ["Machine1", "Machine2"].
Related
- rive-constructor.md
- rive-methods.md
- data-binding.md
- events.md
React Interactive
Use @rive-app/react-canvas with useRive and useStateMachineInput to build an interactive animation that responds to user events.
import { useRive, useStateMachineInput } from "@rive-app/react-canvas";
export default function InteractiveButton() {
const { rive, RiveComponent } = useRive({
src: "button.riv",
stateMachines: "Button State",
autoplay: true,
});
const isHoverInput = useStateMachineInput(rive, "Button State", "isHover");
const onMouseEnter = () => {
if (isHoverInput) isHoverInput.value = true;
};
const onMouseLeave = () => {
if (isHoverInput) isHoverInput.value = false;
};
return (
<div onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave}>
<RiveComponent />
</div>
);
}Notes
useRiveが返すRiveComponentをそのまま JSX に配置すると、canvas のマウント・リサイズ・クリーンアップが自動で管理されるuseStateMachineInputはriveが準備完了するまでnullを返す。操作前に null チェックが必要rive.play()/rive.pause()をRiveComponentのonMouseEnter/onMouseLeaveに直接渡すことで再生制御も可能useDevicePixelRatio(デフォルトtrue)により HiDPI 環境での鮮明なレンダリングが自動で有効になる
samples
| Name | Description | Path |
|---|---|---|
| Web Basic Setup | Load a .riv file onto a canvas element using @rive-app/canvas with minimal configuration and cleanup. | web-basic.md |
| React Interactive | Use @rive-app/react-canvas with useRive and useStateMachineInput to build an interactive animation that responds to user events. | react-interactive.md |
| State Machine Control | Control State Machine inputs (boolean / number / trigger) from code using the web JS runtime. | state-machine-control.md |
State Machine Control
Control State Machine inputs (boolean / number / trigger) from code using the web JS runtime.
import { Rive } from "@rive-app/canvas";
const r = new Rive({
src: "https://cdn.rive.app/animations/vehicles.riv",
canvas: document.getElementById("canvas"),
autoplay: true,
stateMachines: "bumpy",
onLoad: () => {
r.resizeDrawingSurfaceToCanvas();
// Retrieve all inputs for a named state machine
const inputs = r.stateMachineInputs("bumpy");
// Trigger input — fires a one-shot transition
const bumpTrigger = inputs.find((i) => i.name === "bump");
bumpTrigger.fire();
// Number input — set an arbitrary numeric value
const levelInput = inputs.find((i) => i.name === "level");
levelInput.value = 42;
// Boolean input — toggle a state
const isActiveInput = inputs.find((i) => i.name === "isActive");
isActiveInput.value = true;
},
});
// Monitor state changes
r.on("statechange", (event) => {
console.log("current state:", event.data[0]);
});Notes
stateMachineInputs(name)は State Machine がロードされた後(onLoad以降)に呼び出す- Trigger は
.fire()で発火し、状態遷移を一度だけ起こす。Number/Boolean は.valueプロパティへの代入で制御する - 入力名は Rive エディター上で設定した名前と一致させる必要がある(大文字・小文字を区別する)
statechangeイベントで現在のステート名を取得でき、UI との同期やデバッグに使用する
Web Basic Setup
Load a .riv file onto a canvas element using @rive-app/canvas with minimal configuration and cleanup.
<!-- index.html -->
<canvas id="canvas" width="500" height="500"></canvas>import { Rive } from "@rive-app/canvas";
const r = new Rive({
src: "https://cdn.rive.app/animations/vehicles.riv",
canvas: document.getElementById("canvas"),
autoplay: true,
stateMachines: "bumpy",
onLoad: () => {
r.resizeDrawingSurfaceToCanvas();
},
});
// Cleanup when no longer needed
r.cleanup();Notes
resizeDrawingSurfaceToCanvas()はonLoadコールバック内で呼び出し、デバイスピクセル比に合わせてレンダリングを鮮明にするstateMachinesに State Machine 名を渡すと、State Machine が起動した状態でアニメーションが開始されるautoplay: trueを省略するとアニメーションは停止状態で読み込まれるr.cleanup()でメモリリソースを解放する。コンポーネントのアンマウント時・ページ離脱時に呼び出す
Install
各 Rive ランタイムパッケージのインストールコマンド。
Web ランタイム(推奨: WebGL2)
Rive Renderer を使用するフル機能パッケージ。Vector Feathering・Rive Text・スクリプティング等の高度な機能を利用できる。
npm install @rive-app/webgl2yarn add @rive-app/webgl2pnpm add @rive-app/webgl2bun add @rive-app/webgl2Web ランタイム(Canvas)
Rive Renderer を使わない Canvas 2D ベースのパッケージ。高度な機能は利用不可。
npm install @rive-app/canvasyarn add @rive-app/canvaspnpm add @rive-app/canvasWeb ランタイム(Canvas Lite)
Canvas ベースの軽量パッケージ。テキスト・レイアウト・スクリプティング・オーディオ機能が不要な場合に使用する。
npm install @rive-app/canvas-liteyarn add @rive-app/canvas-litepnpm add @rive-app/canvas-liteReact ランタイム(推奨: WebGL2)
@rive-app/webgl2 をラップする React 向けパッケージ。フル機能利用時に推奨。
npm install --save @rive-app/react-webgl2yarn add @rive-app/react-webgl2pnpm add @rive-app/react-webgl2React ランタイム(Canvas)
@rive-app/canvas をラップする React 向けパッケージ。
npm install --save @rive-app/react-canvasyarn add @rive-app/react-canvaspnpm add @rive-app/react-canvasReact ランタイム(Canvas Lite)
バンドルサイズを最小化したい場合の React 向けパッケージ。Rive Text 等の高度な機能は利用不可。
npm install --save @rive-app/react-canvas-liteyarn add @rive-app/react-canvas-litepnpm add @rive-app/react-canvas-liteCDN 経由での読み込み(WebGL2 — 最新版)
HTML に直接 <script> タグで読み込む場合。ビルドツールを使わない環境向け。
<script src="https://unpkg.com/@rive-app/webgl2"></script>CDN 経由での読み込み(WebGL2 — バージョン固定)
本番環境ではバージョンを固定することを推奨する。
<script src="https://unpkg.com/@rive-app/webgl2@2.36.0"></script>バージョン番号は npm で最新版を確認して置き換える(npm show @rive-app/webgl2 version)。
scripts
| Name | Description | Path |
|---|---|---|
| Install | 各 Rive ランタイムパッケージのインストールコマンド(Web / React / CDN) | install.md |