> ## Documentation Index
> Fetch the complete documentation index at: https://rive.app/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Getting Started

> JavaScript/WASM runtime for Rive.

> [!WARNING]
>
> Note that certain Rive features may not be supported yet for a particular runtime, or may require using the Rive Renderer.
>
> For more details, refer to the [feature support](https://rive.app/docs/feature-support.md) and [choosing a renderer](https://rive.app/docs/runtimes/choose-a-renderer/) pages.

## Overview

This guide documents how to get started using the Rive web runtime library. The runtime is open source and available in this [GitHub repository](https://github.com/rive-app/rive-wasm). This library has a high-level JavaScript API (with TypeScript support) and a low-level API to load in Web Assembly (WASM) and control the rendering loop yourself. This runtime allows you to:

* Quickly integrate Rive into all web applications (Webflow, WordPress, etc.)
* Provides a base API to build other web-based Rive runtime wrappers (React, Svelte, etc.)
* Support advanced use cases by controlling the render loop (web-based game engines)

## Getting started

Follow the steps below to integrate Rive into your web app.

These instructions use `@rive-app/webgl2`, the package we recommend for most projects. It draws with the Rive Renderer, the same renderer as the Rive Editor, so it supports everything you can author in Rive including [Vector Feathering](https://rive.app/docs/editor/fundamentals/fill-and-stroke.md#vector-feathering). Rive also publishes Canvas2D packages with a different set of tradeoffs — see [Canvas vs WebGL2](https://rive.app/docs/runtimes/web/canvas-vs-webgl.md). The packages share the same API surface, so you can switch to a different one easily if needed.

**1. Install the dependency**

> [!TIP]
>
> We recommend always using the [latest version](https://www.npmjs.com/package/@rive-app/webgl2) when possible.

> [tab] Script Tag
>
> **(Recommended) Load v2 of the web runtime**
>
> Add the following script tag to your web page to load the latest version of the web runtime:
>
> ```html theme={null}
> <script src="https://unpkg.com/@rive-app/webgl2@latest"></script>
> ```
>
> **Load a pinned version of the web runtime**
>
> Alternatively, pin to a specific version for more control over what is loaded in your app. As Rive's feature set grows, you'll want to manually update this version to a newer one to ensure best compatibility.
>
> ```html theme={null}
> <script src="https://unpkg.com/@rive-app/webgl2@2.40.1"></script>
> ```
>
> This will make a global `rive` object available, allowing you to access the Rive API via the `rive` entry point. Follow the next steps below.

> [tab] Package Manager
>
> ```bash npm theme={null}
> npm install @rive-app/webgl2
> ```
>
> ```bash pnpm theme={null}
> pnpm add @rive-app/webgl2
> ```
>
> ```bash yarn theme={null}
> yarn add @rive-app/webgl2
> ```
>
> ```bash bun theme={null}
> bun add @rive-app/webgl2
> ```
>
> ```javascript Importing theme={null}
> // Import the entire module under the global identifier `rive`
> import * as rive from "@rive-app/webgl2";
>
> // Alternatively, import only the specific parts you need
> import { Rive } from "@rive-app/webgl2";
>
> ```

> [!TIP]
>
> Not using [Rive Text](https://rive.app/docs/editor/text/), [Rive Layouts](https://rive.app/docs/editor/layouts/), [Rive Scripting](https://rive.app/docs/scripting/), or [Rive Audio](https://rive.app/docs/editor/events/audio-events.md)? Consider using [@rive-app/canvas-lite](https://rive.app/docs/runtimes/web/canvas-vs-webgl.md#rive-app-canvas-lite) instead, which is a smaller package variant of our canvas runtime.

**2. Create a Canvas**

Add a canvas element to your HTML where you want the Rive graphic to be displayed:

```html theme={null}
<canvas id="canvas" width="500" height="500"></canvas>
```

**3. Create a Rive instance**

To create a new instance of a Rive object, provide the following properties:

* `src`: A string representing the URL of the hosted `.riv` file (as shown in the example below) or the path to the public asset `.riv` file. For more details, refer to [Rive Parameters](https://rive.app/docs/runtimes/web/rive-parameters.md) on how to properly use this property.
* `artboard` - (Optional) A string representing the artboard you want to display. If not supplied, the default artboard from the `.riv` file is selected.
* `stateMachine` - A string representing the name of the state machine you wish to play. This must be supplied, or the Rive instance may only play the first linear animation it finds. In the next major version, the default behavior will be to play the artboard's default state machine when one exists.
* `canvas` - The canvas element where the animation will be rendered.
* `autoplay` - A boolean indicating whether the animation should play automatically.
* `autoBind` - A boolean indicating whether to automatically data-bind the default `ViewModelInstance` if one is found. We recommend setting this to `true`.

```javascript theme={null}
<script>
    const r = new rive.Rive({
        src: "https://cdn.rive.app/animations/vehicles.riv",
        // OR the path to a discoverable and public Rive asset
        // src: '/public/example.riv',
        canvas: document.getElementById("canvas"),
        autoplay: true,
        autoBind: true,
        // artboard: "Artboard", // Optional. If not supplied the default is selected
        stateMachine: "bumpy",
        onLoad: () => {
          r.resizeDrawingSurfaceToCanvas();
        },
    });
</script>
```

The `resizeDrawingSurfaceToCanvas` method ensures that the Rive animation is correctly scaled to fit the dimensions of the specified canvas element. By default, the canvas rendering surface might not match the exact size of the `<canvas>` element defined in your HTML, which can lead to blurry or incorrectly scaled graphics, especially on high-DPI or retina displays.

Calling this method adjusts the internal drawing surface so that the animation is rendered with crisp detail, matching the pixel density of the canvas. This is particularly important when:

* The size of the canvas changes dynamically (e.g., if it is resized due to responsive layouts).
* You want to ensure the animation remains sharp, regardless of device or screen resolution.

**Best practices:**

* **Call after load**: It's recommended to call `resizeDrawingSurfaceToCanvas` inside the `onLoad` callback to ensure that the Rive asset has been fully loaded before adjusting the drawing surface. This prevents any rendering issues.
* **Handling window resize**: If your canvas size changes during the user's interaction (such as when resizing the browser window), you should also listen for window resize events and call `resizeDrawingSurfaceToCanvas` to re-adjust the rendering surface:

```javascript theme={null}
window.addEventListener("resize", () => {
    r.resizeDrawingSurfaceToCanvas();
});
```

This way, the Rive animation will continue to look sharp and correctly scaled as the canvas size changes.

### Complete example

Bringing it all together, here's how to load a Rive graphic in a single HTML file.

```html theme={null}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Rive Hello World</title>
  </head>
  <body>
    <canvas id="canvas" width="500" height="500"></canvas>

    <script src="https://unpkg.com/@rive-app/webgl2@2.40.1"></script>
    <script>
      const r = new rive.Rive({
        src: "https://cdn.rive.app/animations/vehicles.riv",
        canvas: document.getElementById("canvas"),
        autoplay: true,
        autoBind: true,
        // artboard: "Artboard", // Optional. If not supplied the default is selected
        stateMachine: "bumpy",
        onLoad: () => {
          // Ensure the drawing surface matches the canvas size and device pixel ratio
          r.resizeDrawingSurfaceToCanvas();
        },
      });
    </script>
  </body>
</html>
```

### Loading Rive files

[See this example](https://codesandbox.io/p/sandbox/rive-quick-start-js-xmwcm6?file=%2Fsrc%2Findex.ts) for the different ways to load in a .riv file, the options are:

1. **Hosted URL**: Use a string representing the URL where the `.riv` file is hosted. Set this as the `src` attribute when creating a new Rive instance.
2. **Static Assets in the bundle**: Provide a string with the path to a publicly accessible `.riv` file within your web project. Handle `.riv` files just like any other static asset (e.g., images or fonts) in your project.
3. **Fetching a file**: Instead of using the `src` attribute, use the `buffer` attribute to load an `ArrayBuffer` when fetching a file. This is useful when reusing the same `.riv` file across multiple Rive instances, allowing you to load it only once.
4. **Reusing a Loaded File**: Use the `rivFile` parameter to reuse a previously loaded Rive runtime file object, avoiding the need to fetch it again via the `src` URL or reload it from the `buffer`. This can significantly improve performance by eliminating redundant network requests and loading times, especially when creating multiple Rive instances from the same source. Unlike the `src` and `buffer` parameters, which require parsing under the hood to create a runtime file object, the `riveFile` parameter uses an already parsed object, including any loaded assets. See [Caching a Rive File](https://rive.app/docs/runtimes/web/caching-a-rive-file.md).

For more details, refer to the [Rive Parameters](https://rive.app/docs/runtimes/web/rive-parameters.md) section on the `src` property.

## Clean up Rive

When working with a Rive instance, it's important to properly clean it up when it's no longer needed. This is especially necessary in scenarios where:

* The UI containing Rive animations is no longer needed (e.g., when a modal with Rive graphics is closed).
* The animation or state machine has completed and will not be shown or run again.

Under the hood, Rive creates various low-level objects (such as artboard instances, animation instances, and state machine instances) in C++, which need to be manually deleted to prevent memory leaks. If not cleaned up, these objects can consume unnecessary resources, potentially impacting your application's performance.

Fortunately, the high-level JavaScript API simplifies this process. You don't need to track every object created during the Rive instance lifecycle. Instead, you can clean up all associated objects with a single method call.

To clean up a Rive instance and free up resources, call the following method on your Rive instance:

```javascript theme={null}
const riveInstance = new Rive({...});
...
// When ready to cleanup
riveInstance.cleanup();
```

## Additional Rive web resources

More in-depth Rive web documentation and advanced use cases.

> [card] [Rive Parameters](https://rive.app/docs/runtimes/web/rive-parameters.md)
>
> API docs for the Rive instance.

> [card] [Canvas vs WebGL2](https://rive.app/docs/runtimes/web/canvas-vs-webgl.md)
>
> A guide to the different Rive web packages

> [card] [FAQ](https://rive.app/docs/runtimes/web/faq.md)
>
> Frequently asked questions

> [card] [Preloading WASM](https://rive.app/docs/runtimes/web/preloading-wasm.md)
>
> Instructions on how to preload and self-host the rive WASM library.

> [card] [Low-level API Usage](https://rive.app/docs/runtimes/web/low-level-api-usage.md)
>
> Control the Rive render loop and layout, and draw multiple artboards to the same canvas.

## Examples

* [Basic gallery app](https://github.com/rive-app/rive-wasm/tree/master/js/examples/_frameworks/parcel_example_canvas)
* [Tracking mouse cursor](https://codesandbox.io/p/sandbox/tracking-mouse-cursor-n38gdd?file=%2Fsrc%2Findex.ts)
* [Connecting to page scroll](https://codesandbox.io/p/sandbox/rive-page-scroll-h4msqw?file=%2Fsrc%2Findex.ts%3A27%2C45)
* [Playing state machine only when scrolled into the user's viewport](https://codesandbox.io/p/sandbox/rive-wait-for-scroll-into-view-y9wg8d?file=%2Fsrc%2Findex.ts)
