svelte-canvas

repository·master·Indexed 18 days ago

https://github.com/dnass/svelte-canvas

A library for reactive canvas rendering within Svelte applications, bridging Svelte's reactivity model with HTML5 Canvas drawing. It provides a Canvas component for lifecycle management and a Layer component for composable drawing content. Key features include support for pixel density control, automatic clearing, and a comprehensive set of layer-specific event handlers for mouse, touch, and pointer interactions.

Tokens
1.6K
Snippets
8
Records
10
Agent score
63%

What's inside svelte-canvas

  1. Handle layer-specific events

    master

    When layerEvents is enabled in CanvasProps, you can use LayerEventHandlers to respond to interactions with specific layers. These handlers receive a LayerEvent object containing the coordinates (x, y) and the originalEvent (MouseEvent or TouchEvent).

    Supported layer events include:

    • click, contextmenu, dblclick, auxclick
    • mousedown, mouseup, mousemove
    • mouseenter, mouseleave
    • pointerenter, pointerleave, pointerdown, pointermove, pointerup, pointercancel
    • wheel, touchstart, touchmove, touchend, touchcancel

    Note: For Svelte component usage, these are often prefixed with onlayer. (e.g., onlayer.mouseenter).

    import type { LayerEventHandlers } from 'svelte-canvas';
    
    const layerHandlers: LayerEventHandlers = {
      click: (detail) => {
        console.log(`Layer clicked at: ${detail.x}, ${detail.y}`);
      },
      mousemove: (detail) => {
        // detail.originalEvent is available for standard event properties
      }
    };
  2. Register a layer using the register() function

    master

    To add a layer to the canvas context, use the register function. This function retrieves the internal registration mechanism from the Svelte context using the REGISTER_KEY symbol and executes it with the provided LayerProps. This is typically used within a component that is a child of the main canvas provider to ensure the layer is managed by the LayerManager.

    import { register } from './path/to/registerLayer';
    
    // Inside a Svelte component child of the Canvas provider:
    register({
      // ... LayerProps
    });
  3. Configure the Canvas component with CanvasProps

    master

    The CanvasProps type defines the configuration options for the Svelte Canvas component. You can control dimensions, pixel density, rendering behavior, and event listeners.

    Key properties include:

    • width | height: Dimensions in pixels.
    • pixelRatio: Controls resolution. Can be a number or 'auto'.
    • autoplay: Boolean to control if rendering starts automatically.
    • autoclear: Boolean to determine if the canvas is cleared before each render.
    • layerEvents: Boolean to enable/disable layer-specific event handling.
    • onresize: Callback function receiving a CanvasResizeEvent containing width, height, and pixelRatio.
    • contextSettings: Standard CanvasRenderingContext2DSettings (e.g., alpha, desynchronized).
    • children: A Svelte Snippet for child content.
    import type { CanvasProps } from 'svelte-canvas';
    
    const props: CanvasProps = {
      width: 800,
      height: 600,
      pixelRatio: 'auto',
      autoplay: true,
      autoclear: true,
      layerEvents: true,
      onresize: (detail) => console.log('Resized:', detail),
    };
  4. Define rendering logic with the Render type

    master

    To draw on the canvas, you must provide a render function. The Render type defines the signature for this function, which is called during the animation loop.

    It receives an object containing:

    • context: The CanvasRenderingContext2D used for drawing.
    • width: The current width of the canvas.
    • height: The current height of the canvas.
    • time: The current timestamp (useful for animations).
    import type { Render } from 'svelte-canvas';
    
    const myRender: Render = ({ context, width, height, time }) => {
      context.clearRect(0, 0, width, height);
      context.fillStyle = 'blue';
      context.fillRect(10, 10, 50, 50);
    };
  5. Reference core types: Render, CanvasResizeEvent, and LayerEvent

    master

    The library exports several key types for handling drawing logic and lifecycle events:

    • Render: The type used to define the rendering function for drawing content.
    • CanvasResizeEvent: The event type emitted when the canvas dimensions change.
    • LayerEvent: The event type emitted by layers during their lifecycle.
  6. Reference CanvasProps and CanvasConfig properties

    master

    The following properties are available for configuring the Canvas component via CanvasProps or the internal CanvasConfig object.

    // CanvasProps / CanvasConfig keys
    width: number;
    height: number;
    pixelRatio: number | 'auto';
    class?: ClassValue | null;
    style?: string;
    autoplay?: boolean;
    autoclear?: boolean;
    layerEvents?: boolean;
    onresize?: (detail: CanvasResizeEvent) => void;
    contextSettings?: CanvasRenderingContext2DSettings;
    children?: Snippet;
  7. Use the Layer component

    master

    The Layer component is used to define individual drawing layers within a Canvas component. Layers allow for organized, composable drawing content.

    <script>
      import { Canvas, Layer } from 'svelte-canvas';
    </script>
    
    <Canvas>
      <Layer />
    </Canvas>