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 }} />
Properties
canvas
A reference to the canvas DOM element.
canvas: HTMLCanvasElement;
<script>
let canvas;
$effect(() => {
canvas?.canvas; // HTMLCanvasElement
});
</script>
<Canvas bind:this={canvas} />
context
A reference to the canvas’s 2D rendering context.
context: CanvasRenderingContext2D;
<script>
let canvas;
$effect(() => {
canvas?.context; // CanvasRenderingContext2D
});
</script>
<Canvas bind:this={canvas} />
Methods
redraw
Forces a re-render of the canvas.
redraw(): void;
<script>
let canvas;
$effect(() => {
canvas?.redraw();
});
</script>
<Canvas bind:this={canvas} />
Component events
onresize
Fires when the canvas is resized or the pixel ratio changes.
type CanvasResizeEvent = {
width: number;
height: number;
pixelRatio: number;
};
<script>
import { Canvas, type CanvasResizeEvent } from 'svelte-canvas';
Â
const onresize = (e: CanvasResizeEvent) => console.log(e.width);
</script>
Â
<Canvas {onresize} />
DOM event handling
DOM event handlers added to the Canvas
component will be forwarded to the canvas element. For example:
<Canvas onclick={() => console.log("clicked")} />
Events can also be handled at the layer level. See the Layer
component for more information.