Canvas

Canvas is the top-level element. It’s a Svelte wrapper around an HTML <canvas> element. Only Layer components, or components that wrap a Layer, are valid children of Canvas.

Props

width

When unset, the canvas will use the width of its parent element.

width: number = canvas.parentElement.clientWidth;

height

When unset, the canvas will use the height of its parent element.

height: number = canvas.parentElement.clientHeight;

pixelRatio

If pixelRatio is unset, the canvas uses Svelte’s devicePixelRatio binding to match the window’s pixel density.

If pixelRatio is set to 'auto', the canvas-size library is used to automatically calculate the maximum supported pixel ratio based on the browser and canvas size. This can be particularly useful when rendering large canvases on iOS Safari.

pixelRatio: number | 'auto' = window.devicePixelRatio ?? 2;

style

A CSS style string which will be applied to the canvas element.

style: string | null = null;

class

A class string which will be applied to the canvas element.

class: string | null = null;

autoplay

If true, child layers will render with each tick of the animation loop. Otherwise, layers will only render when a child layer’s render dependencies change.

autoplay: boolean = false;

autoclear

If true, will use context.clearRect to clear the canvas at the start of each render cycle.

autoclear: boolean = true;

layerEvents

If true, enables event handling on child Layer components. This has a performance cost, so it’s disabled by default.

layerEvents: boolean = false;

contextSettings

A settings object passed to canvas.getContext.

contextSettings: CanvasRenderingContext2DSettings | undefined = undefined;
<Canvas contextSettings={{ alpha: false }} />

Methods

getCanvas

Returns a reference to the canvas DOM element.

getCanvas(): HTMLCanvasElement;
<script>
  let canvas;
  $: canvas?.getCanvas(); // HTMLCanvasElement
</script>

<Canvas bind:this={canvas} />

getContext

Returns a reference to the canvas’s 2D rendering context.

getContext(): CanvasRenderingContext2D;
<script>
  let canvas;
  $: canvas?.getContext(); // CanvasRenderingContext2D
</script>

<Canvas bind:this={canvas} />

redraw

Forces a re-render of the canvas.

redraw(): void;
<script>
  let canvas;
  $: canvas?.redraw();
</script>

<Canvas bind:this={canvas} />

Events

resize

Fires when the canvas is resized or the pixel ratio changes.

resize: CustomEvent<{ width: number; height: number; pixelRatio: number; }>;
<Canvas on:resize={(e) => console.log(e.detail.width)} />

Event handling

DOM event handlers added to the Canvas component will be forwarded to the canvas element. For example:

<Canvas on:click={() => console.log("clicked")} />

Events can also be handled at the layer level. See the Layer component for more information.