@fartinmartin/svelte-canvas v0.0.2
@fartinmartin/svelte-canvas
A ✨responsive✨ svelte-canvas fork using code plucked from vb-canvas.
Installation
npm install @fartinmartin/svelte-canvas
Usage
<script lang="ts">
import { Canvas, Layer, t } from "@fartinmartin/svelte-canvas";
import type { CanvasFunction } from "@fartinmartin/svelte-canvas";
let setup: CanvasFunction; // optional function
$: setup = () => {};
let render: CanvasFunction;
$: render = ({ context, width, height }) => {
context.fillStyle = `hsl(${$t / 40}, 100%, 50%)`;
context.beginPath();
context.arc(($t / 4) % width, ($t / 4) % height, 100, 0, Math.PI * 2);
context.fill();
};
import { onMount } from "svelte";
let canvas: Canvas;
onMount(() => {
const can = canvas.getCanvas();
const ctx = canvas.getContext();
console.log(can, ctx);
canvas.redraw();
});
</script>
<Canvas width={640} height={640} bind:this={canvas}>
<Layer {render} />
</Canvas>More examples:
API
Canvas
Canvas is the top-level element. It's a Svelte wrapper around an HTML <canvas> element.
Parameters
| parameter | default | description |
|---|---|---|
width | 640 | Canvas width |
height | 640 | Canvas height |
pixelRatio | window.devicePixelRatio | Canvas pixel ratio |
style | null | A CSS style string which will be applied to the canvas element |
autoclear | true | If true, will use context.clearRect to clear the canvas at the start of each render cycle |
autoAspectRatio | true | Match DOM dimensions to viewBox. When true, <canvas> elements behave in a similar way to <svg>. |
scaleMode | fit | VBCanvas's version of preserveAspectRatio. Accepts fit or fill. fit is equal to SVG'sxMidYMid meet. fill is equal to SVG'sxMidYMid slice. |
isStatic | false | Retains canvas drawing on resize, without the need of an animation loop. |
Methods
| method | description |
|---|---|
getCanvas | Returns a reference to the canvas DOM element |
getContext | Returns the canvas's 2D rendering context |
redraw | Forces a re-render of the canvas |
Events
All DOM events on the <canvas> element are forwarded to the Canvas component, so handling an event is as simple as <Canvas on:click={handleClick}>.
Layer
Layer is a layer to be rendered onto the canvas. It takes two props, setup and render Both take functions with a single argument that receives an object with the properties context, width, and height. context is the 2D rendering context of the parent canvas. width and height are the canvas's dimensions.
setup is optional and is called once at initialization. render is called every time the canvas redraws.
Declaring your render function reactively allows svelte-canvas to re-render anytime the values that the function depends on change.
t
t is a readable store that provides the time in milliseconds since initialization. Subscribing to t within your render function lets you easily create animations.