Play an animation

It’s helpful to understand the difference between an animation and an artboard. An animation is a set of keyframes that can be applied to a set of objects in an artboard. The animation instance tracks the keyframes as they change over time.

Web
Flutter
iOS
Android
Web

1. Create a canvas and context

First, you'll need to create a canvas and content for the renderer

const canvas = document.getElementById('riveCanvas');
const ctx = canvas.getContext('2d');
const renderer = new rive.CanvasRenderer(ctx);

Advance the artboard to render a frame

artboard.advance(0);

2. Set your alignment and fit

The renderer has different fit and align options available to it. Here we center it and proportionately fit it to the canvas

ctx.save();
renderer.align(rive.Fit.contain, rive.Alignment.center, {
minX: 0,
minY: 0,
maxX: canvas.width,
maxY: canvas.height
}, artboard.bounds);

Now we can draw our frame to our canvas

artboard.draw(renderer);
ctx.restore();

3. Setup your animation loop

The recommended method for creating a render loop in Javascript is to use requestAnimationFrame. You can find more information on this from MDN. Start by keeping track of the last time a frame was rendered

let lastTime = 0;

Then define your draw method

function draw(time) {
if (!lastTime) {
lastTime = time;
}
const elapsedTime = (time - lastTime) / 1000;
lastTime = time;
myAnimInstance.advance(elapsedTime);
myAnimInstance.apply(artboard, 1.0);
artboard.advance(elapsedTime);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
renderer.align(rive.Fit.contain, rive.Alignment.center, {
minX: 0,
minY: 0,
maxX: canvas.width,
maxY: canvas.height
}, artboard.bounds);
artboard.draw(renderer);
ctx.restore();
requestAnimationFrame(draw);
}
Flutter

iOS

Stay tuned for information on our upcoming iOS runtime!

Android

Stay tuned for information on our upcoming Android runtime!