The Kineto web runtime plays a .kvk file in the browser, using the Kineto engine compiled to WebAssembly. Cody, the bear on the Kineto homepage, runs on it. The example below uses the same file and inputs as iOS Playback.
Get access
Clone the repository and use the checked-in files from runtimes/web/pkg, or follow its README and scripts/build_runtime_web.sh to rebuild them. Record the exact source revision. Serve the files over HTTP(S), not file://.
The web runtime has three files, which belong in the same folder:
kineto_engine.jskineto_engine_bg.wasm- your
.kvkfile
When redistributing the generated runtime, include its THIRD_PARTY_NOTICES.md and licenses/RUST_LICENSE_TEXTS.txt alongside your distribution, and review their requirements. The runtime’s MIT license does not grant rights to somebody else’s artwork.
Example file
Download cody.kvk, the runtime file the Kineto homepage plays.
| Item | Value |
|---|---|
| State machine id | cfba0cd6-7a60-4851-a8d2-d312b67b5392 |
| Inputs | tapped-left-eye, tapped-right-eye (bool) |
The web runtime has no call that lists machines or inputs. For your own file, read these values from the handoff notes. To get the notes, keep the handoff option on when you export the .kvk.
Complete example
This example was run in Chromium, including a real click on Cody’s left eye and the error cases below.
The page
The canvas needs an id, because renderToCanvas finds it by id. touch-action: none stops a touch on the canvas from scrolling the page.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Cody on the web</title>
<style>
#cody { display: block; width: 100%; max-width: 480px; aspect-ratio: 1; touch-action: none; }
</style>
</head>
<body>
<canvas id="cody" role="img" aria-label="Cody the bear. Tap an eye to make him wink."></canvas>
<p id="cody-fallback" hidden>The animation could not load.</p>
<button type="button" data-input="tapped-left-eye" disabled>Wink left</button>
<button type="button" data-input="tapped-right-eye" disabled>Wink right</button>
<script type="module" src="./cody.js"></script>
</body>
</html>
The script
Save this as cody.js.
import init, { KinetoWasmPlayer } from './kineto_engine.js';
const FILE_URL = './cody.kvk';
const MACHINE_ID = 'cfba0cd6-7a60-4851-a8d2-d312b67b5392';
const MAX_PIXEL_RATIO = 2;
const canvas = document.getElementById('cody');
const fallback = document.getElementById('cody-fallback');
const buttons = document.querySelectorAll('[data-input]');
function showFallback(error) {
console.error('Kineto:', error);
stop();
canvas.hidden = true;
fallback.hidden = false;
buttons.forEach((button) => (button.disabled = true));
}
async function loadPlayer() {
await init(); // Loads kineto_engine_bg.wasm from the same folder as the module.
const response = await fetch(FILE_URL);
if (!response.ok) throw new Error(`${FILE_URL}: HTTP ${response.status}`);
return new KinetoWasmPlayer(new Uint8Array(await response.arrayBuffer()));
}
let player;
let frame = 0;
let lastTime = 0;
let onScreen = true;
function resize() {
const ratio = Math.min(window.devicePixelRatio || 1, MAX_PIXEL_RATIO);
const width = Math.round(canvas.clientWidth * ratio);
const height = Math.round(canvas.clientHeight * ratio);
if (width > 0 && height > 0 && (canvas.width !== width || canvas.height !== height)) {
canvas.width = width;
canvas.height = height;
}
}
function tick(now) {
frame = 0;
try {
// Cap the step, so a long pause doesn't skip the animation forward.
player.advance(lastTime ? Math.min((now - lastTime) / 1000, 0.1) : 0);
player.renderToCanvas(canvas.id);
} catch (error) {
showFallback(error);
return;
}
lastTime = now;
start();
}
function start() {
if (player && !frame && onScreen && !document.hidden) frame = requestAnimationFrame(tick);
}
function stop() {
if (frame) cancelAnimationFrame(frame);
frame = 0;
lastTime = 0;
}
function sendPointer(type, event) {
const rect = canvas.getBoundingClientRect();
const x = ((event.clientX - rect.left) / rect.width) * canvas.width;
const y = ((event.clientY - rect.top) / rect.height) * canvas.height;
const point = player.documentPoint(x, y, canvas.width, canvas.height);
player.pointerEvent(type, point[0], point[1]);
}
function tap(input) {
player.setBool(MACHINE_ID, input, true);
setTimeout(() => player.setBool(MACHINE_ID, input, false), 220);
}
try {
player = await loadPlayer();
} catch (error) {
showFallback(error);
}
if (player) {
resize();
new ResizeObserver(resize).observe(canvas);
new IntersectionObserver(([entry]) => {
onScreen = entry.isIntersecting;
if (onScreen) start();
else stop();
}).observe(canvas);
document.addEventListener('visibilitychange', () => {
if (document.hidden) stop();
else start();
});
canvas.addEventListener('pointerdown', (event) => {
canvas.setPointerCapture(event.pointerId);
sendPointer('down', event);
});
canvas.addEventListener('pointerup', (event) => sendPointer('up', event));
canvas.addEventListener('pointercancel', (event) => sendPointer('up', event));
buttons.forEach((button) => {
button.disabled = false;
button.addEventListener('click', () => tap(button.dataset.input));
});
start();
}
The script does the following:
- Errors: if the runtime or the file can’t load, or drawing fails, it hides the canvas and shows the fallback text.
- Sharpness: the canvas buffer follows the CSS size and the pixel density. The density is capped at 2 to save power.
- Resizing: a
ResizeObserverupdates the buffer. The runtime fits the artboard into whatever size the canvas has. - Pausing: drawing stops when the canvas leaves the screen or the tab is hidden, and starts again when it returns.
- Time: each step is capped at 0.1 seconds, and the first frame after a pause advances by 0.
- Taps: pointer positions go from CSS pixels to canvas pixels, then through
documentPointto document coordinates.
Inputs and state
On the web, the state machine id comes first.
player.setBool(MACHINE_ID, 'tapped-left-eye', true); // Cody blends to Wink.
player.setBool(MACHINE_ID, 'tapped-left-eye', false); // Cody blends back to Idle.
const stateId = player.activeState(MACHINE_ID);
const transitionId = player.activeTransition(MACHINE_ID); // undefined when no blend is running.
activeState returns a state id, not a name. Files with other input types use setTrigger(machineId, name) and setNumber(machineId, name, value), with a value from 0 to 1. The public runtime source supports host-set numbers; the editor’s old runtime v1 skips label was incorrect. Engine and web binding fixtures are tested; see Known Limitations for platform evidence.
pointerEvent accepts 'down', 'up', 'enter' and 'exit', and returns how many listeners fired.
Errors
The calls throw a message, which you can catch as in the script above. lastError() returns the most recent message.
| Situation | Message |
|---|---|
The .kvk file returns 404 |
The HTTP 404 error from the script |
The data isn’t a .kvk file |
A format error, for example Type i32 at position ... is unaligned |
| The input name is wrong | Unknown input name "..." |
| The machine id is wrong | Unknown state machine id "..." |
What the web runtime draws
The web runtime draws to a 2D canvas, and it draws less than the iOS runtime. It doesn’t draw text, images, blur, shadows or blend modes, and gradients become a single color. Check the support table before you design for the web.
Hosting
Two different headers affect how kineto_engine_bg.wasm loads. They do different things.
| Header | What it controls | If it’s missing |
|---|---|---|
Content-Type: application/wasm |
Whether the browser can use WebAssembly.instantiateStreaming, which compiles the file while it downloads |
The runtime logs a console warning, downloads the whole file, then compiles it. It still works |
Content-Encoding: gzip or br |
Whether the file is compressed on the way to the browser | The browser downloads the full file. It still works |
The two are independent: compression doesn’t depend on the MIME type in the browser, and streaming doesn’t depend on compression. Some servers only compress the types they’re configured for, so check both.
We tested all four combinations of these headers in Chromium, using gzip. Each one loaded and played Cody. With gzip, the transfer dropped from 591,902 to 203,122 bytes.
Check your server:
curl -sI -H 'Accept-Encoding: gzip, br' https://example.com/kineto_engine_bg.wasm \
| grep -iE '^content-(type|encoding)'
You should see content-type: application/wasm and a content-encoding line.
By default, init() loads the .wasm file from the same folder as kineto_engine.js. To load it from another location, pass the URL: init({ module_or_path: url }). A different origin needs CORS headers. A strict Content Security Policy needs 'wasm-unsafe-eval' in script-src.
Testing checklist
- The runtime and the
.kvkfile load without errors - The fallback text appears when you block the
.kvkfile - The canvas is sharp on high-density screens
- A tap on an eye and both buttons make Cody wink
- Drawing stops in a hidden tab
- Performance is acceptable on phones as well as desktops