# Web Engines

Set up a Glint game with plain Canvas, Phaser, Three.js or KAPLAY: starters, bundler settings, a complete SDK integration for each, pause and mute handling, and packaging the build.

The SDK works with any engine that runs in a browser. This page shows the same integration for plain Canvas, Phaser, Three.js and KAPLAY, taken from the starters that `glint init` creates. Pick your engine on any code block and the rest of the page follows.

## Start a Project

```bash tab="Canvas"
glint init vanilla-ts my-game
glint preview my-game
```

```bash tab="Phaser"
glint init phaser my-game
cd my-game
npm install
npm run build
npx glint preview dist
```

```bash tab="Three.js"
glint init threejs my-game
cd my-game
npm install
npm run build
npx glint preview dist
```

```bash tab="KAPLAY"
glint init kaplay my-game
cd my-game
npm install
npm run build
npx glint preview dist
```

The Canvas starter has no build step: its folder is the build. The Phaser, Three.js and KAPLAY starters use Vite and depend on `@joinfoundry/glint-sdk`, Phaser 3, Three.js or KAPLAY from npm. Their `npm run build` script runs `vite build` and copies `glint.json` into `dist`.

> [!NOTE]
> The build script copies the manifest with `cp`. On Windows, where npm runs scripts with `cmd.exe`, that step fails; copy `glint.json` into `dist` yourself after `vite build`.

`npm run dev` starts Vite's dev server, where the SDK runs in [standalone mode](https://joinfoundry.xyz/help/developers/glint-sdk-api#standalone-mode). Use `glint preview dist` to test against Glint's sandbox.

## Bundler Settings

The Vite starters ship this `vite.config.ts`:

```ts
import { defineConfig } from "vite";

export default defineConfig({
  base: "./",
  build: {
    sourcemap: false,
    target: "es2022",
  },
});
```

- `base: "./"` makes every asset path relative, which Glint requires ([GL005](https://joinfoundry.xyz/help/developers/glint-sdk-cli#gl005)).
- `sourcemap: false` keeps `.map` files out of the build ([GL104](https://joinfoundry.xyz/help/developers/glint-sdk-cli#gl104)).
- Install the engine from npm and let Vite bundle it. Loading Phaser, Three.js or KAPLAY from a CDN is blocked by the sandbox ([GL003](https://joinfoundry.xyz/help/developers/glint-sdk-cli#gl003)).

## index.html

```html tab="Canvas"
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" />
  <title>Glint Starter</title>
  <style>
    html, body { margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; background: #0b0a1a; color: #f3f2ff; font-family: system-ui, sans-serif; }
    canvas { display: block; width: 100%; height: 100%; touch-action: none; }
  </style>
</head>
<body>
  <canvas id="game"></canvas>
  <script src="./glint.js"></script>
  <script type="module" src="./main.js"></script>
</body>
</html>
```

```html tab="Phaser"
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" />
  <title>Phaser Foundry Starter</title>
  <style>
    html, body, #app { margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; background: #0b0a1a; }
  </style>
</head>
<body>
  <div id="app"></div>
  <script type="module" src="./src/main.ts"></script>
</body>
</html>
```

```html tab="Three.js"
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" />
  <title>Three.js Foundry Starter</title>
  <style>
    html, body { margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; background: #0b0a1a; }
    canvas { display: block; width: 100%; height: 100%; }
  </style>
</head>
<body>
  <script type="module" src="./src/main.ts"></script>
</body>
</html>
```

```html tab="KAPLAY"
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" />
  <title>KAPLAY Foundry Starter</title>
  <style>
    html, body { margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; background: #0b0a1a; }
  </style>
</head>
<body>
  <script type="module" src="./src/main.ts"></script>
</body>
</html>
```

Every page fills the frame with `width: 100%; height: 100%; overflow: hidden`. The Canvas page loads the SDK from `./glint.js`; the Vite pages import it from npm inside `src/main.ts`, so Vite bundles it.

## Integrate the SDK

Each example starts the SDK, sizes the canvas within `maxDpr`, follows master mute, stops on pause and calls `ready()` once the first scene is up.

```js tab="Canvas"
// main.js
const canvas = document.getElementById("game");
const ctx = canvas.getContext("2d");

let paused = false;
let muted = false;
let rafId = 0;

function resize(maxDpr) {
  const dpr = Math.min(2, maxDpr);
  const rect = canvas.getBoundingClientRect();
  canvas.width = Math.max(1, Math.floor(rect.width * dpr));
  canvas.height = Math.max(1, Math.floor(rect.height * dpr));
}

async function boot() {
  const sdk = await window.Glint.init();
  sdk.lifecycle.loadingProgress(0.4);

  muted = sdk.system.isMuted();
  const hints = sdk.system.getHints();
  resize(hints.maxDpr);
  new ResizeObserver(() => resize(hints.maxDpr)).observe(canvas);

  const saved = await sdk.saves.load("main");
  const bestScore = typeof saved?.data?.bestScore === "number" ? saved.data.bestScore : 0;

  const tick = () => {
    if (paused) return;
    ctx.fillStyle = "#0b0a1a";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = "#f3f2ff";
    ctx.font = "700 20px system-ui, sans-serif";
    ctx.fillText(`${sdk.player.get().displayName} · Best: ${bestScore} · ${muted ? "Muted" : "Audio On"}`, 20, 40);
    rafId = requestAnimationFrame(tick);
  };

  sdk.lifecycle.onPause(() => {
    paused = true;
    cancelAnimationFrame(rafId);
    void sdk.saves.flush();
  });
  sdk.lifecycle.onResume(() => {
    if (!paused) return;
    paused = false;
    rafId = requestAnimationFrame(tick);
  });
  sdk.system.onMuteChange(next => {
    muted = next;
  });

  sdk.lifecycle.loadingProgress(1);
  sdk.lifecycle.ready();
  sdk.lifecycle.gameplayStart();
  rafId = requestAnimationFrame(tick);
}

void boot();
```

```ts tab="Phaser"
// src/main.ts
import Phaser from "phaser";
import { Glint } from "@joinfoundry/glint-sdk";

async function start() {
  const sdk = await Glint.init();
  sdk.lifecycle.loadingProgress(0.25);

  class MainScene extends Phaser.Scene {
    private player!: Phaser.GameObjects.Arc;
    private cursors!: Phaser.Types.Input.Keyboard.CursorKeys;

    create() {
      this.sound.mute = sdk.system.isMuted();
      this.player = this.add.circle(400, 225, 20, 0xc6ff2e);
      this.cursors = this.input.keyboard!.createCursorKeys();
      this.add.text(16, 16, `Welcome, ${sdk.player.get().displayName}`, { color: "#f3f2ff", fontFamily: "system-ui" });
      sdk.lifecycle.loadingProgress(1);
      sdk.lifecycle.ready();
      sdk.lifecycle.gameplayStart();
    }

    update(_t: number, delta: number) {
      const speed = 0.28 * delta;
      if (this.cursors.left.isDown) this.player.x -= speed;
      if (this.cursors.right.isDown) this.player.x += speed;
      if (this.cursors.up.isDown) this.player.y -= speed;
      if (this.cursors.down.isDown) this.player.y += speed;
    }
  }

  const game = new Phaser.Game({
    type: Phaser.AUTO,
    parent: "app",
    backgroundColor: "#0b0a1a",
    scale: { mode: Phaser.Scale.RESIZE, autoCenter: Phaser.Scale.CENTER_BOTH, width: "100%", height: "100%" },
    scene: [MainScene],
  });

  sdk.lifecycle.onPause(() => {
    game.loop.sleep();
    game.sound.mute = true;
    void sdk.saves.flush();
  });
  sdk.lifecycle.onResume(() => {
    game.sound.mute = sdk.system.isMuted();
    game.loop.wake();
  });
  sdk.system.onMuteChange(muted => {
    game.sound.mute = muted;
  });
}

void start();
```

```ts tab="Three.js"
// src/main.ts
import * as THREE from "three";
import { Glint } from "@joinfoundry/glint-sdk";

async function start() {
  const sdk = await Glint.init();
  const hints = sdk.system.getHints();

  const renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: "high-performance" });
  renderer.setPixelRatio(Math.min(2, hints.maxDpr));
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);

  const scene = new THREE.Scene();
  scene.background = new THREE.Color(0x0b0a1a);
  const camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 100);
  camera.position.z = 3.2;

  const cube = new THREE.Mesh(
    new THREE.BoxGeometry(1, 1, 1),
    new THREE.MeshStandardMaterial({ color: 0xc6ff2e, roughness: 0.35 }),
  );
  scene.add(cube);
  const light = new THREE.DirectionalLight(0xffffff, 2.2);
  light.position.set(2, 3, 4);
  scene.add(light, new THREE.AmbientLight(0xb9a5f2, 0.8));

  const resize = () => {
    camera.aspect = window.innerWidth / Math.max(1, window.innerHeight);
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
  };
  new ResizeObserver(resize).observe(document.body);

  let paused = false;
  let rafId = 0;
  let last = performance.now();
  const loop = (now: number) => {
    if (paused) return;
    const dt = Math.min(0.05, (now - last) / 1000);
    last = now;
    cube.rotation.x += dt * 0.8;
    cube.rotation.y += dt * 1.1;
    renderer.render(scene, camera);
    rafId = requestAnimationFrame(loop);
  };

  sdk.lifecycle.onPause(() => {
    paused = true;
    cancelAnimationFrame(rafId);
    void sdk.saves.flush();
  });
  sdk.lifecycle.onResume(() => {
    if (!paused) return;
    paused = false;
    last = performance.now();
    rafId = requestAnimationFrame(loop);
  });

  sdk.lifecycle.ready();
  sdk.lifecycle.gameplayStart();
  rafId = requestAnimationFrame(loop);
}

void start();
```

```ts tab="KAPLAY"
// src/main.ts
import kaplay from "kaplay";
import { Glint } from "@joinfoundry/glint-sdk";

async function start() {
  const sdk = await Glint.init();
  const k = kaplay({
    background: [11, 10, 26],
    pixelDensity: Math.min(2, sdk.system.getHints().maxDpr),
  });

  k.setVolume(sdk.system.isMuted() ? 0 : 1);
  sdk.system.onMuteChange(muted => k.setVolume(muted ? 0 : 1));
  sdk.lifecycle.onPause(() => {
    k.debug.paused = true;
    k.setVolume(0);
    void sdk.saves.flush();
  });
  sdk.lifecycle.onResume(() => {
    k.debug.paused = false;
    k.setVolume(sdk.system.isMuted() ? 0 : 1);
  });

  const player = k.add([k.rect(36, 36), k.pos(k.width() / 2, k.height() / 2), k.color(198, 255, 46), k.anchor("center")]);
  k.onKeyDown("left", () => player.move(-260, 0));
  k.onKeyDown("right", () => player.move(260, 0));
  k.onKeyDown("up", () => player.move(0, -260));
  k.onKeyDown("down", () => player.move(0, 260));

  sdk.lifecycle.ready();
  sdk.lifecycle.gameplayStart();
}

void start();
```

## Pause, Resume and Mute

| Engine | On pause | On resume | Master mute |
| --- | --- | --- | --- |
| Canvas | Set a `paused` flag and `cancelAnimationFrame()` | Clear the flag and request a new frame | Track `muted` and apply it to your audio |
| Phaser | `game.loop.sleep()` and `game.sound.mute = true` | `game.loop.wake()` and restore `game.sound.mute` from `sdk.system.isMuted()` | `game.sound.mute = muted` |
| Three.js | `cancelAnimationFrame()` behind a `paused` flag | Reset the frame clock and request a new frame | Apply it to your audio (the starter has none) |
| KAPLAY | `k.debug.paused = true` and `k.setVolume(0)` | `k.debug.paused = false` and restore the volume | `k.setVolume(muted ? 0 : 1)` |

Each example also calls `sdk.saves.flush()` on pause. The SDK flushes pending saves on pause by itself, so this is a safeguard for engines that keep running briefly.

Pass your loader's real progress to `sdk.lifecycle.loadingProgress()`. In Phaser, report the preloader's progress events and call `ready()` in the first scene's `create()`, as the example does. Keep the first scene small and load later levels after `ready()` to stay within the 2 MB Loads Fast budget.

## Multiplayer

For online play, start from the `multiplayer-ts` starter, a Canvas arena with Quick Join, Create Room and Invite buttons, 8-byte binary position updates about 15 times a second, invite links and host migration:

```bash
glint init multiplayer-ts my-arena
glint preview my-arena --players 2
```

The same room code works in any engine. See [Multiplayer Rooms](https://joinfoundry.xyz/help/developers/glint-sdk-api#multiplayer-rooms) for the API and [Multi-Player Room Lab](https://joinfoundry.xyz/help/developers/glint-sdk-cli#multi-player-room-lab) for testing.

## Other Web Engines

PixiJS, Babylon.js, WebAssembly builds and other engines follow the Canvas pattern: start from `vanilla-ts` or your own bundler setup, set `engine` in `glint.json` (`pixijs`, `babylon`, `wasm` or `other`), make asset paths relative, cap the pixel ratio at `Math.min(2, sdk.system.getHints().maxDpr)`, and stop the render loop on pause.

## Build, Check and Zip

```bash tab="Canvas"
glint validate my-game
```

```bash tab="Phaser"
npm run build
npx glint validate dist
```

```bash tab="Three.js"
npm run build
npx glint validate dist
```

```bash tab="KAPLAY"
npm run build
npx glint validate dist
```

Then zip the contents of the folder you validated, so `index.html` and `glint.json` are at the top level of the ZIP, and upload it in Glint Studio. See [Upload a Build](https://joinfoundry.xyz/help/glint/upload-a-build).

> [!TIP]
> A Vite build bundles the SDK into your script, and the SDK's standalone fallback uses `localStorage`, so `validate` shows warning [GL103](https://joinfoundry.xyz/help/developers/glint-sdk-cli#gl103) even when your own code uses `sdk.saves`. You can ignore it in that case.
