Skip to content

Instantly share code, notes, and snippets.

@seanharmer
Created February 6, 2024 14:12
Show Gist options
  • Save seanharmer/ce949f7a4beeefbb0918526fe040a4ca to your computer and use it in GitHub Desktop.
Save seanharmer/ce949f7a4beeefbb0918526fe040a4ca to your computer and use it in GitHub Desktop.
Rive Stimulus
<canvas
data-controller="rive"
data-rive-url-value="<%= asset_path("button1.riv") %>"
data-rive-state-machines-value="State Machine 1"
class="mt-16 w-full aspect-video bg-black"
>
</canvas>
import { Controller } from "@hotwired/stimulus"
const rive = require("@rive-app/canvas");
// Connects to data-controller="rive"
export default class extends Controller {
static values = { url: String, stateMachines: String }
connect() {
const layout = new rive.Layout({
fit: rive.Fit.FitWidth, // Change to: rive.Fit.Contain, or Cover
alignment: rive.Alignment.Center,
});
this.riveInstance = new rive.Rive({
src: this.urlValue, // URL to the Rive file
stateMachines: this.stateMachinesValue, // Name of the State Machine to play
canvas: this.element, // Canvas element to render to
layout: layout,
autoplay: true,
onLoad: () => {
// Prevent a blurry canvas by using the device pixel ratio
this.riveInstance.resizeDrawingSurfaceToCanvas();
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment