Class CanvasSandbox<TCanvas, TApplicationOptions>

The CanvasSandbox provides a scaffold to quickly perform experiments with a HTMLCanvasElement in a document. Common functionality for such experiments is implemented in the sandbox already.

import { Random, seedFromString } from "@oliversalzburg/js-utils/lib/random.js";
import { Canvas } from "@oliversalzburg/js-utils/lib/graphics/canvas.js";
import { getDocumentElementTypeByIdStrict } from "@oliversalzburg/js-utils/lib/dom/core.js";
import { CanvasSandbox } from "@oliversalzburg/js-utils/lib/graphics/canvas-sandbox.js";

interface ApplicationOptions {
seed: string;
somethingElse: number;
}

class Application {
canvas: Canvas;
options: ApplicationOptions;
random: Random;

constructor(canvas:Canvas, options: ApplicationOptions) {
this.canvas = canvas;
this.options = options;
this.random = new Random(seedFromString(options.seed));
}

reconfigure(canvas:Canvas, options: Partial<ApplicationOptions> = {}) {
this.canvas = canvas;
this.options = { ...this.options, ...options };
this.random = new Random(seedFromString(options.seed));
}

onDraw(delta:number, timestamp:number) {
// draw something on `this.canvas`
}

start() {}
}

const canvasNode = getDocumentElementTypeByIdStrict(document, "main", HTMLCanvasElement);
const canvasSandbox = new CanvasSandbox(
window,
canvasNode,
Application,
{seed: "foo", somethingElse: 12345}
);

// By running the sandbox, your `start()` and `onDraw()` methods will automatically be invoked
// by the sandbox. You shouldn't invoke those methods directly from your own code.
canvasSandbox.run();
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
</head>

<body>
<canvas id="main" class="darkMode" width="512" height="512"></canvas>
</body>
<script src="main.ts" type="module"></script>
</html>

Type Parameters

Constructors

Properties

The application running inside the sandbox.

canvas: TCanvas

Our convenience canvas wrapper, which we provide to the application to render to.

canvasNode: HTMLCanvasElement

The canvas node that we're drawing into.

document: Document

The document the sandbox is interacting with.

renderLoop: RenderLoop

The render loop we use to control frame rendering.

sandboxOptions: Partial<CanvasSandboxOptions>

The options for this sandbox.

shakeHandler: Shake

Our handler for device shaking.

window: Window

The window the sandbox is running in.

Methods