Preview & playback
Mount the player on a canvas and control playback.
The player turns the project into pixels and sound on a <canvas>. The quickest way to put one on the page:
import { createPreviewController } from "@miraiclip/renderer";
import { project } from "./project";
const canvas = document.querySelector<HTMLCanvasElement>("#preview")!;
const button = document.querySelector<HTMLButtonElement>("#play")!;
const preview = createPreviewController(project);
preview.attach(canvas, { width: canvas.clientWidth, height: canvas.clientHeight });
button.addEventListener("click", () => preview.toggle());
preview.subscribe(() => {
button.textContent = preview.getState().playing ? "Pause" : "Play";
});
// When the view goes away:
// preview.destroy();Also uses project.ts
import { createProject } from "@miraiclip/core";
// One project instance for the whole app. Pass it to components as a prop.
export const project = createProject({ width: 1280, height: 720, fps: 30 });import { Preview, usePlayback } from "@miraiclip/react";
// Inside <ProjectProvider> and <PlaybackProvider>.
export function PreviewPanel() {
const { isPlaying, toggle } = usePlayback();
return (
<>
{/* Hands its canvas to <PlaybackProvider>, keeps it sized, releases it on unmount. */}
<Preview width={640} height={360} />
<button type="button" onClick={toggle}>
{isPlaying ? "Pause" : "Play"}
</button>
</>
);
}<script setup lang="ts">
import { onBeforeUnmount, onMounted, shallowRef, useTemplateRef } from "vue";
import type { Project } from "@miraiclip/core";
import { createPreviewController } from "@miraiclip/renderer";
const props = defineProps<{ project: Project }>();
const canvas = useTemplateRef<HTMLCanvasElement>("canvas");
const preview = createPreviewController(props.project);
const state = shallowRef(preview.getState());
const stop = preview.subscribe(() => (state.value = preview.getState()));
onMounted(() => {
const el = canvas.value!;
preview.attach(el, { width: el.clientWidth, height: el.clientHeight });
});
onBeforeUnmount(() => {
stop();
preview.destroy();
});
</script>
<template>
<canvas ref="canvas" style="width: 640px; height: 360px" />
<button @click="preview.toggle()">{{ state.playing ? "Pause" : "Play" }}</button>
</template><script lang="ts">
import type { Project } from "@miraiclip/core";
import { createPreviewController, type PreviewController } from "@miraiclip/renderer";
let { project }: { project: Project } = $props();
let canvas = $state<HTMLCanvasElement>();
let playing = $state(false);
let preview: PreviewController | undefined;
$effect(() => {
if (!canvas) return;
const controller = createPreviewController(project);
preview = controller;
const stop = controller.subscribe(() => (playing = controller.getState().playing));
controller.attach(canvas, { width: canvas.clientWidth, height: canvas.clientHeight });
return () => {
stop();
controller.destroy();
preview = undefined;
};
});
</script>
<canvas bind:this={canvas} style="width: 640px; height: 360px"></canvas>
<button onclick={() => preview?.toggle()}>{playing ? "Pause" : "Play"}</button><Preview> hands its canvas to PlaybackProvider, keeps the render target matched to its size and releases it on unmount. Fit-to-parent sizing, overlays and every prop: Components › Preview.
The vanilla version expects <canvas id="preview"> and <button id="play"> on the page; give the canvas a CSS size.
createPreviewController builds the renderer and player on the canvas and keeps them in step with it. Vue and Svelte components are planned; until then, use the controller directly, as above.
The rest of this page is what runs underneath: the preview controller, which every framework uses, and the player it builds.
Preview controller
createPreviewController(project, options?) owns everything between the canvas and the player:
| Handles | How |
|---|---|
| Building the renderer | attach(canvas, size) creates the WebGL backend and player. A second attach on the same canvas reuses them |
| StrictMode and fast remounts | An attach → detach → attach while the backend is still building ends with one renderer, never two on one WebGL context |
| No WebCodecs or WebGL | mode is "unsupported" or "fallback", and a plain clock still moves the playhead so timelines keep working |
| Sharp output, bounded memory | The render target is the canvas's CSS size × devicePixelRatio (capped at 2); decoding never exceeds what the preview shows |
| Monitoring volume | setVolume(v) and toggleMute() change only what you hear, never the project or exports |
| GPU memory pressure | A lost WebGL context tells the player to shrink its frame budget |
| Member | What it does |
|---|---|
getState(), subscribe(listener) | { playing, mode, lastError, volume, muted }; a new object on every change |
play(), pause(), toggle(), seek(us) | Transport. seek clamps to the composition |
attach(canvas, size), resize(w, h), detach() | Canvas lifecycle; sizes are CSS pixels |
getClipBounds(id), hitTest(x, y, filter?) | Geometry of what is on screen, in composition pixels |
player | The live player, or null |
destroy() | Detach and drop listeners |
| Option | Default | Use |
|---|---|---|
backend | createPixiBackend options, e.g. htmlRaster | |
player | createPlayer options, e.g. memory, loop, factories | |
maxDecodeDimensionPx | 1920 | Longest decoded frame side |
maxPixelRatio | 2 | devicePixelRatio cap |
initialVolume | 1 | Starting monitoring volume |
beforeLive(project) | Awaited before the preview goes live, e.g. to load web fonts | |
onPlayerReady(player), onError(error, clipId) | Hooks for dev overlays and error reporting |
Building the player yourself
The controller is built from createPixiBackend and createPlayer. To wire them up yourself:
import type { Project } from "@miraiclip/core";
import {
createPixiBackend,
createPlayer,
createWebAudioOutput,
createWebCodecsDecoderFactory,
isWebCodecsSupported,
openMediabunnyAudio,
openMediabunnyDemuxer,
type Player,
} from "@miraiclip/renderer";
export async function mountPlayer(canvas: HTMLCanvasElement, project: Project): Promise<Player> {
if (!isWebCodecsSupported()) throw new Error("This browser has no WebCodecs");
const { width, height } = project.getState().doc.settings;
const dpr = Math.min(devicePixelRatio, 2); // sharp on hi-DPI, capped for speed
return createPlayer(project, {
backend: await createPixiBackend({ canvas, width, height }),
openDemuxer: openMediabunnyDemuxer,
createDecoder: createWebCodecsDecoderFactory({ maxOutputDimensionPx: 1920 }),
audioOutput: createWebAudioOutput(),
openAudio: openMediabunnyAudio,
outputSize: { width: canvas.clientWidth * dpr, height: canvas.clientHeight * dpr },
});
}Player API
| Member | What it does |
|---|---|
play() / pause() | Start and stop playback |
seek(us) | Jump to a time in µs |
setRate(rate) | Playback speed |
playing, timeUs, durationUs | Read-only transport state |
on(type, listener) | Transport events: play, pause (with reason: "pause" or "ended"), ended, seek, ratechange, error. Returns an unsubscribe function |
rate | Current playback speed |
getClipBounds(clipId, timeUs?) | Where a clip is drawn, in composition pixels |
hitTest(x, y, options?) | Topmost clip at a point: use it for click-to-select |
destroy() | Release decoders, audio and the GPU context |
Use the events instead of polling player.playing: a player stops on its own at the end of the composition, and pause tells you why.
player.on("pause", ({ reason }) => {
if (reason === "ended") showReplayButton();
});StrictMode mounts effects twice in development. PlaybackProvider and the preview controller handle it: you get one renderer, not two.