Rive Instance Methods Reference¶
This document provides a comprehensive guide to all methods available on a Rive instance, including public and private methods, with usage examples and context.
Table of Contents¶
- Creating a Rive Instance
- Animation Control Methods
- State Machine Methods
- ViewModels and ViewModelInstance Methods
- Text and Input Methods
- Layout and Rendering Methods
- Event Management Methods
- Property Getters and Setters
- Cleanup Methods
- Private Methods
Creating a Rive Instance¶
Constructor¶
Creates a new Rive instance.Example:
const rive = new Rive({
canvas: document.getElementById('canvas'),
src: 'animation.riv',
autoplay: true,
stateMachines: 'State Machine 1',
layout: new Layout({
fit: Fit.Cover,
alignment: Alignment.Center
})
});
Static Constructor (Deprecated)¶
Alternative constructor - deprecated, usenew Rive() instead. Animation Control Methods¶
play()¶
Plays specified animations. If none specified, it unpauses everything.Example:
// Play a single animation
rive.play('idle');
// Play multiple animations
rive.play(['idle', 'walk']);
// Resume all paused animations
rive.play();
pause()¶
Pauses specified animations. If none specified, pauses all.Example:
scrub()¶
Scrubs animations to a specific time value.Example:
stop()¶
Stops specified animations. If none specified, stops them all.Example:
reset()¶
Resets the animation with optional new parameters.Example:
load()¶
Loads a new Rive file, keeping listeners in place.Example:
State Machine Methods¶
stateMachineInputs()¶
Returns the inputs for the specified instanced state machine.Example:
const inputs = rive.stateMachineInputs('State Machine 1');
inputs.forEach(input => {
console.log(input.name, input.type);
});
setBooleanStateAtPath()¶
Sets a boolean input value at a specific path in nested artboards.Example:
// Set boolean state in nested artboard
rive.setBooleanStateAtPath('isActive', true, 'nested/artboard/path');
setNumberStateAtPath()¶
Sets a number input value at a specific path.Example:
// Set number state in nested artboard
rive.setNumberStateAtPath('speed', 50, 'character/movement');
fireStateAtPath()¶
Fires a trigger input at a specific path.Example:
ViewModels and ViewModelInstance Methods¶
viewModelByName()¶
Gets a view model by its name from the Rive file.Example:
const viewModel = rive.viewModelByName('PlayerData');
if (viewModel) {
console.log('Found view model:', viewModel.name);
console.log('Instance count:', viewModel.instanceCount);
}
viewModelByIndex()¶
Gets a view model by its index in the file.Example:
const viewModel = rive.viewModelByIndex(0);
if (viewModel) {
const instance = viewModel.defaultInstance();
}
defaultViewModel()¶
Returns the default view model for the current artboard.Example:
const defaultVM = rive.defaultViewModel();
if (defaultVM) {
const instance = defaultVM.instance();
// Work with the instance
}
bindViewModelInstance()¶
Binds a view model instance to the artboard and state machines.Example:
const viewModel = rive.viewModelByName('GameData');
const instance = viewModel?.defaultInstance();
if (instance) {
rive.bindViewModelInstance(instance);
// Now you can manipulate the instance
instance.number('score')?.value = 100;
instance.string('playerName')?.value = 'Player 1';
}
enums()¶
Returns all data enums defined in the Rive file.Example:
const enums = rive.enums();
enums.forEach(dataEnum => {
console.log('Enum:', dataEnum.name);
console.log('Values:', dataEnum.values);
});
ViewModel Class Methods¶
When you retrieve a ViewModel from the Rive instance:
instanceByName()¶
Gets a specific instance of the view model by name.Example:
const viewModel = rive.viewModelByName('PlayerData');
const instance = viewModel?.instanceByName('Player1');
instanceByIndex()¶
Gets an instance by its index.defaultInstance()¶
Gets the default instance of the view model.instance()¶
Creates a new instance of the view model.ViewModelInstance Methods¶
When working with a ViewModelInstance:
Property Access Methods¶
number()¶
Access a number property at the given path.Example:
const instance = viewModel.defaultInstance();
const scoreProperty = instance?.number('player/score');
if (scoreProperty) {
scoreProperty.value = 150;
console.log('Score:', scoreProperty.value);
}
string()¶
Access a string property.Example:
const nameProperty = instance?.string('player/name');
if (nameProperty) {
nameProperty.value = 'John Doe';
}
boolean()¶
Access a boolean property.Example:
const isActiveProperty = instance?.boolean('player/isActive');
if (isActiveProperty) {
isActiveProperty.value = true;
}
color()¶
Access a color property.Example:
const colorProperty = instance?.color('theme/primaryColor');
if (colorProperty) {
colorProperty.rgb(255, 0, 0); // Set to red
colorProperty.opacity(0.8); // Set opacity
}
trigger()¶
Access a trigger property.Example:
const triggerProperty = instance?.trigger('actions/reset');
triggerProperty?.trigger(); // Fire the trigger
enum()¶
Access an enum property.Example:
const stateProperty = instance?.enum('player/state');
if (stateProperty) {
console.log('Available states:', stateProperty.values);
stateProperty.value = 'running';
// Or by index
stateProperty.valueIndex = 1;
}
list()¶
Access a list property.Example:
const itemsList = instance?.list('inventory/items');
if (itemsList) {
console.log('List length:', itemsList.length);
// Add a new instance
const newItem = viewModel.instance();
itemsList.addInstance(newItem);
// Remove at index
itemsList.removeInstanceAt(0);
// Swap items
itemsList.swap(0, 1);
}
image()¶
Access an image property.Example:
const imageProperty = instance?.image('avatar/picture');
if (imageProperty) {
// Decode and set a new image
const imageBytes = await fetch('avatar.png').then(r => r.arrayBuffer());
const decodedImage = await decodeImage(new Uint8Array(imageBytes));
imageProperty.value = decodedImage;
}
viewModel()¶
Access a nested view model instance.Example:
const nestedInstance = instance?.viewModel('player/stats');
if (nestedInstance) {
nestedInstance.number('health')?.value = 100;
}
replaceViewModel()¶
Replace a nested view model with another instance.Example:
const newStatsInstance = statsViewModel.instance();
const success = instance.replaceViewModel('player/stats', newStatsInstance);
Text and Input Methods¶
getTextRunValue()¶
Gets the text value from a text run node.Example:
setTextRunValue()¶
Sets the text value for a text run node.Example:
getTextRunValueAtPath()¶
Gets text from nested artboards.Example:
setTextRunValueAtPath()¶
Sets text in nested artboards.Example:
Layout and Rendering Methods¶
drawFrame()¶
Manually draws the current artboard frame.Example:
resizeToCanvas()¶
Sets the layout bounds to the current canvas size.Example:
resizeDrawingSurfaceToCanvas()¶
Accounts for devicePixelRatio when rendering.Example:
// Resize with default device pixel ratio
rive.resizeDrawingSurfaceToCanvas();
// Or with custom ratio
rive.resizeDrawingSurfaceToCanvas(2);
setupRiveListeners()¶
Sets up touch/mouse listeners for state machine interactions.Example:
removeRiveListeners()¶
Removes all Rive listeners from the canvas.startRendering()¶
Starts the rendering loop if previously stopped.stopRendering()¶
Stops the rendering loop without changing animation state.Example:
// Stop rendering when tab is not visible
document.addEventListener('visibilitychange', () => {
if (document.hidden) {
rive.stopRendering();
} else {
rive.startRendering();
}
});
enableFPSCounter()¶
Enables FPS reporting.Example:
// Show default FPS counter
rive.enableFPSCounter();
// Or with custom callback
rive.enableFPSCounter((fps) => {
console.log('Current FPS:', fps);
});
disableFPSCounter()¶
Disables FPS reporting.Event Management Methods¶
on()¶
Subscribe to Rive-generated events.Example:
rive.on(EventType.Load, () => {
console.log('Rive loaded!');
});
rive.on(EventType.StateChange, (event) => {
console.log('States changed:', event.data);
});
rive.on(EventType.RiveEvent, (event) => {
console.log('Rive event:', event.data);
});
off()¶
Unsubscribe from events.Example:
const handler = (event) => console.log(event);
rive.on(EventType.Loop, handler);
// Later...
rive.off(EventType.Loop, handler);
removeAllRiveEventListeners()¶
Remove all listeners of a specific type or all listeners.Example:
// Remove all loop listeners
rive.removeAllRiveEventListeners(EventType.Loop);
// Remove all listeners
rive.removeAllRiveEventListeners();
Property Getters and Setters¶
Animation Properties¶
isPlaying¶
Returns true if any animation is playing.isPaused¶
Returns true if all animations are paused.isStopped¶
Returns true if no animations are playing or paused.playingAnimationNames¶
Returns names of currently playing animations.playingStateMachineNames¶
Returns names of currently playing state machines.Artboard Properties¶
activeArtboard¶
Returns the name of the active artboard.bounds¶
Returns the bounds of the current artboard.artboardWidth / artboardHeight¶
public get artboardWidth(): number
public set artboardWidth(value: number)
public get artboardHeight(): number
public set artboardHeight(value: number)
Example:
File Properties¶
source¶
Returns the animation source URL.contents¶
Returns the contents of the Rive file.Example:
const contents = rive.contents;
contents?.artboards.forEach(artboard => {
console.log('Artboard:', artboard.name);
console.log('Animations:', artboard.animations);
console.log('State Machines:', artboard.stateMachines);
});
animationNames¶
Returns all animation names in the current artboard.stateMachineNames¶
Returns all state machine names in the current artboard.Audio/Video Properties¶
volume¶
Get/set the artboard volume (0-1).Example:
Layout Properties¶
layout¶
Get/set the layout configuration.Example:
Performance Properties¶
fps¶
Returns current frames per second.frameTime¶
Returns average frame time in milliseconds.Cleanup Methods¶
cleanup()¶
Cleans up all WASM-generated objects. Call this when done with the Rive instance.Example:
deleteRiveRenderer()¶
Cleans up only the renderer object.cleanupInstances()¶
Cleans up artboard, animation, and state machine instances.resetArtboardSize()¶
Resets the artboard to its original dimensions.Private Methods¶
These methods are used internally but documented for completeness:
init()¶
Initializes the Rive object from constructor or load().initData()¶
Initializes runtime with Rive data.initArtboard()¶
Initializes artboard for playback.draw()¶
Main rendering loop method.alignRenderer()¶
Aligns the renderer with current layout settings.onSystemAudioChanged()¶
Handles audio context availability changes.onCanvasResize()¶
Handles canvas resize events.Best Practices¶
- Always clean up: Call
cleanup()when done with a Rive instance - Handle events: Use event listeners for load, error, and state changes
- Check for null: Many methods return null if the resource isn't found
- Use paths for nested content: Use forward slashes for nested artboard paths
- Batch operations: When making multiple changes, they'll be applied in the next render frame
Example of proper usage:
const rive = new Rive({
canvas: document.getElementById('canvas'),
src: 'animation.riv',
autoplay: false,
onLoad: () => {
// Setup after load
const vm = rive.defaultViewModel();
const instance = vm?.defaultInstance();
if (instance) {
rive.bindViewModelInstance(instance);
// Set initial values
instance.string('playerName')?.value = 'Player 1';
instance.number('score')?.value = 0;
}
// Start playing
rive.play('idle');
},
onLoadError: (e) => {
console.error('Failed to load:', e);
}
});
// Clean up on page unload
window.addEventListener('beforeunload', () => {
rive.cleanup();
});
Animation Class¶
The Animation class manages the state and behavior of a single animation instance. This is typically managed internally by Rive, but understanding it can be helpful.
Properties¶
loopCount¶
Tracks how many times the animation has looped.instance¶
The underlying WASM animation instance.scrubTo¶
The time to scrub to on the next render (used internally).playing¶
Whether the animation is currently playing.Methods¶
name¶
Returns the animation's name.time¶
Get/set the animation's current time.loopValue¶
Returns the animation's loop type (0=one-shot, 1=loop, 2=ping-pong).needsScrub¶
Indicates whether the animation needs to be scrubbed.advance()¶
Advances the animation by the given time.apply()¶
Applies interpolated keyframe values to the artboard.cleanup()¶
Deletes the backing WASM animation instance.Asset Loading Functions¶
decodeAudio()¶
Decodes bytes into an audio asset. Be sure to call.unref() on the audio once it's no longer needed. Example:
const audioBytes = await fetch('sound.mp3').then(r => r.arrayBuffer());
const audio = await decodeAudio(new Uint8Array(audioBytes));
// Use the audio with an AudioAsset
audioAsset.setAudioSource(audio);
// Clean up when done
audio.unref();
decodeImage()¶
Decodes bytes into an image. Be sure to call.unref() on the image once it's no longer needed. Example:
const imageBytes = await fetch('sprite.png').then(r => r.arrayBuffer());
const image = await decodeImage(new Uint8Array(imageBytes));
// Use the image with an ImageAsset
imageAsset.setRenderImage(image);
// Clean up when done
image.unref();
decodeFont()¶
Decodes bytes into a font. Be sure to call.unref() on the font once it's no longer needed. Example:
const fontBytes = await fetch('custom-font.ttf').then(r => r.arrayBuffer());
const font = await decodeFont(new Uint8Array(fontBytes));
// Use the font with a FontAsset
fontAsset.setFont(font);
// Clean up when done
font.unref();
RuntimeLoader¶
Static class for managing the WASM runtime loading.
Static Methods¶
getInstance()¶
Provides a runtime instance via a callback.Example:
RuntimeLoader.getInstance((runtime) => {
// Use the runtime
const renderer = runtime.makeRenderer(canvas);
});
awaitInstance()¶
Provides a runtime instance via a promise.Example:
setWasmUrl()¶
Manually sets the WASM URL before loading.Example:
getWasmUrl()¶
Gets the current WASM URL.RiveFile Class¶
Manages loading and lifecycle of a Rive file.
Constructor¶
Methods¶
init()¶
Initializes the Rive file.getInstance()¶
Gets the underlying file instance (increases reference count).cleanup()¶
Decreases reference count and cleans up if no more references.on() / off()¶
public on(type: EventType, callback: EventCallback): void
public off(type: EventType, callback: EventCallback): void
Example:
const riveFile = new RiveFile({
src: 'animation.riv',
onLoad: () => console.log('File loaded'),
onLoadError: (e) => console.error('Load error:', e)
});
await riveFile.init();
Layout Class¶
Manages how Rive content is positioned and scaled within the canvas.
Constructor¶
Methods¶
copyWith()¶
Creates a copy of the layout with modified parameters.Example:
Important Enums and Types¶
Fit Enum¶
export enum Fit {
Cover = "cover",
Contain = "contain",
Fill = "fill",
FitWidth = "fitWidth",
FitHeight = "fitHeight",
None = "none",
ScaleDown = "scaleDown",
Layout = "layout"
}
Alignment Enum¶
export enum Alignment {
Center = "center",
TopLeft = "topLeft",
TopCenter = "topCenter",
TopRight = "topRight",
CenterLeft = "centerLeft",
CenterRight = "centerRight",
BottomLeft = "bottomLeft",
BottomCenter = "bottomCenter",
BottomRight = "bottomRight"
}
EventType Enum¶
export enum EventType {
Load = "load",
LoadError = "loaderror",
Play = "play",
Pause = "pause",
Stop = "stop",
Loop = "loop",
Draw = "draw",
Advance = "advance",
StateChange = "statechange",
RiveEvent = "riveevent",
AudioStatusChange = "audiostatuschange"
}
StateMachineInputType Enum¶
LoopType Enum¶
RiveEventType Enum¶
Type Definitions¶
AssetLoadCallback¶
Custom asset loader callback type.EventCallback¶
Event handler callback type.FPSCallback¶
FPS reporting callback type.Testing Utilities¶
Testing Export¶
Exports for testing purposes only - not for production use.// Clean up on page unload window.addEventListener('beforeunload', () => { rive.cleanup(); });
Private Methods¶
Important Note: Private methods are internal implementation details and are NOT meant to be called directly by users. They are documented here for completeness and to help understand the internal workings of the Rive runtime. Attempting to access these methods directly may break your code in future versions.
Core Initialization Methods¶
init()¶
Initializes the Rive object either from constructor or load(). Sets up the runtime, renderer, and starts the loading process.Internal Usage Example:
// Called internally in constructor
this.init({
src: this.src,
buffer: this.buffer,
riveFile: this.riveFile,
autoplay: params.autoplay,
animations: params.animations,
stateMachines: params.stateMachines,
artboard: params.artboard,
useOffscreenRenderer: params.useOffscreenRenderer,
});
initData()¶
private async initData(
artboardName: string,
animationNames: string[],
stateMachineNames: string[],
autoplay: boolean,
autoBind: boolean
): Promise<boolean>
Internal Usage:
// Called internally during initialization
this.initData(artboard, startingAnimationNames, startingStateMachineNames, autoplay, autoBind)
.then((hasInitialized) => {
if (hasInitialized) {
return this.setupRiveListeners();
}
});
initArtboard()¶
private initArtboard(
artboardName: string,
animationNames: string[],
stateMachineNames: string[],
autoplay: boolean,
autoBind: boolean
): void
initializeAudio()¶
Sets up audio context if the artboard has audio components.initArtboardSize()¶
Initializes artboard dimensions using preset values or defaults.Rendering Methods¶
draw()¶
Main rendering loop method. Advances animations, applies changes, and renders the frame.Internal Flow:
// Automatically called in the render loop
// 1. Calculate elapsed time
// 2. Advance animations and state machines
// 3. Apply changes to artboard
// 4. Clear canvas and draw
// 5. Handle events (loops, state changes)
// 6. Request next frame if playing
alignRenderer()¶
Aligns the renderer according to the current layout settings.Internal Usage:
Event Handling Methods¶
onSystemAudioChanged()¶
Event handler for when audio context becomes available. Updates volume settings.onCanvasResize¶
Arrow function that handles canvas resize events from the ResizeObserver.Internal Behavior: - Tracks when canvas has zero size - Triggers resizing of drawing surface when canvas becomes visible - Updates layout bounds if needed
Data Retrieval Methods¶
retrieveTextRun()¶
Retrieves a text run node from the artboard with error handling.Internal Usage:
// Used by public getTextRunValue() method
const textRun = this.retrieveTextRun(textRunName);
return textRun ? textRun.text : undefined;
retrieveInputAtPath()¶
Retrieves a state machine input at a specific path in nested artboards.Internal Usage:
// Used by public methods like setBooleanStateAtPath()
const input = this.retrieveInputAtPath(inputName, path);
if (input && input.type === StateMachineInputType.Boolean) {
input.asBool().value = value;
}
retrieveTextAtPath()¶
Retrieves text at a specific path in nested artboards.Static Methods (RuntimeLoader class)¶
loadRuntime()¶
Loads the WASM runtime, handling fallback URLs if the primary fails.Internal Behavior: 1. Attempts to load from unpkg CDN 2. Falls back to jsDelivr if unpkg fails 3. Fires callbacks once loaded 4. Handles errors with detailed logging
Internal Classes Private Methods¶
AudioManager Private Methods¶
delay()¶
Creates a promise that resolves after specified milliseconds.timeout()¶
Creates a promise that rejects after 50ms for audio testing.enableAudio()¶
Enables audio once context is available.testAudio()¶
Tests if audio context can be resumed._establishAudio()¶
Main method to establish audio, polling until available.reportToListeners()¶
Notifies listeners of audio status changes.listenForUserAction()¶
Sets up click listener to enable audio on user interaction.EventManager Private Methods¶
getListeners()¶
Returns all listeners of a specific event type.ObjectObservers Private Methods¶
_onObservedEntry()¶
Handles individual resize observer entries._onObserved()¶
Handles multiple resize observer entries.RiveFile Private Methods¶
initData()¶
Loads Rive file data from source or buffer.fireLoadError()¶
Fires load error event and throws error.ViewModelInstance Private Methods¶
clearCallbacks()¶
Clears all callbacks from properties.propertyFromPath()¶
Retrieves a property at a given path.Internal Usage:
// Used by public property access methods
public number(path: string): ViewModelInstanceNumber | null {
const viewmodelInstanceValue = this.propertyFromPath(path, PropertyType.Number);
return viewmodelInstanceValue as ViewModelInstanceNumber;
}
viewModelFromPathSegments()¶
private viewModelFromPathSegments(
pathSegments: string[],
index: number
): ViewModelInstance | null
propertyFromPathSegments()¶
private propertyFromPathSegments(
pathSegments: string[],
index: number,
type: PropertyType
): ViewModelInstanceValue | null
internalViewModelInstance()¶
Gets or creates a view model instance with proper reference counting.StateMachine Private Methods¶
initInputs()¶
Fetches and caches state machine inputs.mapRuntimeInput()¶
Maps runtime inputs to appropriate typed wrappers.Understanding Private Method Access¶
While you cannot directly call private methods, you might need to understand them for:
- Debugging: Understanding the call stack when errors occur
- Extending: Creating custom classes that extend Rive functionality
- Contributing: Contributing to the Rive runtime source code
- Performance: Understanding the internal render loop for optimization
Example of Understanding Internal Flow:
// When you call play(), internally it triggers:
// 1. taskQueue processing if not ready
// 2. animator.play()
// 3. setupRiveListeners() if needed
// 4. startRendering() which calls draw()
// 5. draw() runs the render loop
// Understanding this helps debug issues like:
// - Why animations don't start immediately
// - How state changes are propagated
// - When listeners are attached/detached
Accessing Internal State (Not Recommended):
// While technically possible in JavaScript, accessing private fields is discouraged:
// DON'T DO THIS - may break in future versions
const internalLayout = rive._layout; // Bad practice
// DO THIS instead - use public API
const publicLayout = rive.layout; // Good practice
Best Practices¶
- Always clean up: Call
cleanup()when done with a Rive instance - Handle events: Use event listeners for load, error, and state changes
- Check for null: Many methods return null if the resource isn't found
- Use paths for nested content: Use forward slashes for nested artboard paths
- Batch operations: When making multiple changes, they'll be applied in the next render frame
Example of proper usage: ```javascript const rive = new Rive({ canvas: document.getElementById('canvas'), src: 'animation.riv', autoplay: false, onLoad: () => { // Setup after load const vm = rive.defaultViewModel(); const instance = vm?.defaultInstance(); if (instance) { rive.bindViewModelInstance(instance);
// Set initial values
instance.string('playerName')?.value = 'Player 1';
instance.number('score')?.value = 0;
}
// Start playing
rive.play('idle');
}, onLoadError: (e) => { console.error('Failed to load:', e); } });
// Clean up on page unload window.addEventListener('beforeunload', () => { rive.cleanup(); });