### Install svelte-canvas Source: https://github.com/dnass/svelte-canvas/blob/master/src/routes/+page.svx Instructions to install the svelte-canvas library using npm. This is the primary step to begin using the library in your Svelte project. ```text npm install svelte-canvas ``` -------------------------------- ### Svelte Layer with Setup and Motion Source: https://context7.com/dnass/svelte-canvas/llms.txt Shows a Svelte Layer component with both `setup` and `render` functions. The `setup` function initializes reactive motion springs for `x` and `y` coordinates, positioning them in the center. The `render` function draws a circle at these dynamic coordinates. ```svelte ``` -------------------------------- ### Importing Svelte Components and Data Source: https://github.com/dnass/svelte-canvas/blob/master/src/routes/examples/layer-events/+page.svx This script block imports necessary Svelte components ('App', 'Example') and prepares data for the Example component. It sets up the main application component within a shared example layout. ```javascript import App from './App.svelte'; import Example from '../../_components/Example.svelte'; export let data; ``` -------------------------------- ### Layer Props: Setup Function Signature (TypeScript) Source: https://github.com/dnass/svelte-canvas/blob/master/src/routes/components/layer/+page.svx Defines the TypeScript signature for the 'setup' prop of the Layer component. Similar to the 'render' function, it provides access to the canvas context, dimensions, and time, but is executed only once during layer initialization. ```typescript setup: (props: { context: CanvasRenderingContext2D; width: number; height: number; time: number; }): void; ``` -------------------------------- ### Render App Component within Example - Svelte Source: https://github.com/dnass/svelte-canvas/blob/master/src/routes/examples/reactive-render/+page.svx This Svelte script renders the main App component inside a reusable Example component. The Example component likely handles aspect ratio and file data, while App manages the core canvas functionality. No external libraries are explicitly imported for this rendering logic itself. ```svelte ``` -------------------------------- ### Svelte Canvas Component Setup Source: https://context7.com/dnass/svelte-canvas/llms.txt Demonstrates the basic usage of the Canvas component in Svelte. It initializes canvas properties like dimensions, pixel ratio, and autoplay behavior, and includes a simple render function for the background. The `onresize` handler logs canvas dimension changes. ```svelte ``` -------------------------------- ### Canvas DOM Event Handling Example Source: https://github.com/dnass/svelte-canvas/blob/master/src/routes/components/canvas/+page.svx Demonstrates how standard DOM events, such as click events, can be directly attached to the Canvas component. These events are automatically forwarded to the underlying canvas element, simplifying event management. ```html console.log("clicked")} /> ``` -------------------------------- ### Svelte Layer Component Rendering Source: https://context7.com/dnass/svelte-canvas/llms.txt Illustrates the use of the Layer component within Svelte Canvas to draw text. It defines a render function that sets font styles and displays 'hello world' centered on the canvas. This example assumes the Canvas component is already set up. ```svelte ``` -------------------------------- ### Canvas Resize Event Definition and Handling Source: https://github.com/dnass/svelte-canvas/blob/master/src/routes/components/canvas/+page.svx Defines the structure for resize events emitted by the Canvas component, including width, height, and pixel ratio. An example demonstrates how to listen for and handle these events, logging the new dimensions. ```typescript type CanvasResizeEvent = { width: number; height: number; pixelRatio: number; }; ``` ```html ``` -------------------------------- ### Create Interactive Draggable Layer with svelte-canvas and Svelte Motion Source: https://context7.com/dnass/svelte-canvas/llms.txt Combines layer events with Svelte's motion springs to create smooth, interactive canvas elements. This example allows a layer to be dragged and dynamically changes its size on hover and drag. ```svelte ``` -------------------------------- ### Layer Event Handling Example (Svelte) Source: https://github.com/dnass/svelte-canvas/blob/master/src/routes/components/layer/+page.svx Demonstrates enabling and using event handling for Layer components within a Canvas. When `layerEvents` is true on the parent Canvas, individual Layers can respond to events like clicks. The event object passed to the handler includes coordinates relative to the canvas and the original DOM event. ```svelte   console.log(e.x, e.y)} /> ``` -------------------------------- ### Layer Component Usage with Inline Render Function (Svelte) Source: https://github.com/dnass/svelte-canvas/blob/master/src/routes/components/layer/+page.svx Illustrates using the Layer component with an inline render function directly in the template. This example shows how to render the elapsed time, centered on the canvas, by accessing the 'context', 'width', 'height', and 'time' properties passed to the render function. ```svelte { context.fillText(time, width / 2, height / 2); }} /> ``` -------------------------------- ### Handle Layer Events with svelte-canvas Source: https://context7.com/dnass/svelte-canvas/llms.txt Enables layer-level event detection by setting `layerEvents={true}` on the Canvas. Each Layer can then handle mouse and touch events with pixel-perfect hit detection. This example demonstrates click, mouse enter, and mouse leave events. ```svelte ``` -------------------------------- ### Svelte Component Structure - Globe Source: https://github.com/dnass/svelte-canvas/blob/master/src/routes/examples/globe/+page.svx This Svelte script block defines the structure and imports for the Globe component. It imports the main 'App' component and a reusable 'Example' component, likely for displaying code or demos. The 'data.files' prop is passed down to the Example component. ```svelte ``` -------------------------------- ### Render Type Definition (TypeScript) Source: https://github.com/dnass/svelte-canvas/blob/master/src/routes/components/layer/+page.svx Defines the TypeScript interface for the 'Render' type, used for typing the setup and render functions within the Layer component. This interface ensures that these functions receive the expected properties: context, width, height, and time. ```typescript interface Render { (props: { context: CanvasRenderingContext2D; width: number; height: number; time: number; }): void; } ``` -------------------------------- ### Layer Component API Source: https://context7.com/dnass/svelte-canvas/llms.txt The Layer component represents an individual drawing surface or element on the canvas. It accepts a render function and optionally a setup function, and can participate in event handling if enabled on the parent Canvas. ```APIDOC ## Layer Component ### Description The Layer component defines a rendering function that draws on the canvas. Layers render in the order they appear in the DOM and can optionally handle mouse and touch events when the Canvas has `layerEvents` enabled. ### Props - **setup** (function) - Optional - A function that runs once before the first render, useful for initialization. Receives `{ context, width, height }`. - **render** (function) - Required - The function responsible for drawing on the canvas. Receives `{ context, width, height, time }`. ### Usage Examples **Basic Layer:** ```svelte ``` **Layer with Setup Function:** ```svelte ``` ``` -------------------------------- ### Render Function Signature Definition (TypeScript) Source: https://context7.com/dnass/svelte-canvas/llms.txt Defines the `Render` type for Svelte Canvas layer render and setup functions. It provides access to the `context`, canvas `width`, `height`, and elapsed `time` since initialization. ```typescript import type { Render } from 'svelte-canvas'; const myRenderFunction: Render = ({ context, width, height, time }) => { // context: CanvasRenderingContext2D // width: number - canvas logical width // height: number - canvas logical height // time: number - milliseconds since Canvas initialization context.fillStyle = `hsl(${(time / 10) % 360}, 70%, 50%)`; context.fillRect(0, 0, width, height); }; ``` -------------------------------- ### Create Responsive Canvas with Auto Sizing in svelte-canvas Source: https://context7.com/dnass/svelte-canvas/llms.txt Shows how to create a responsive canvas using svelte-canvas that automatically resizes to fill its parent container. When width and height are omitted, the Canvas adjusts to size changes and the `onresize` event provides updated dimensions. ```svelte
``` -------------------------------- ### Canvas Component API Source: https://github.com/dnass/svelte-canvas/blob/master/src/routes/components/canvas/+page.svx This section details the props, properties, methods, and events associated with the Canvas component. ```APIDOC ## Canvas Component API ### Description The `Canvas` component is the top-level element in svelte-canvas, acting as a Svelte wrapper around an HTML `` element. It is designed to contain `Layer` components or custom components that wrap a `Layer`. ### Props * **width** (number | undefined) - The width of the canvas. If unset, it defaults to the width of the parent element. * **height** (number | undefined) - The height of the canvas. If unset, it defaults to the height of the parent element. * **pixelRatio** (number | 'auto' | undefined) - The pixel ratio for the canvas. Defaults to the window's device pixel ratio or 2. Can be set to `'auto'` to use the `canvas-size` library for automatic calculation. * **style** (string | null) - A CSS style string to be applied to the canvas element. * **class** (ClassValue | null) - A class string or `ClassValue` to be applied to the canvas element. * **autoplay** (boolean) - If `true`, child layers render automatically with each animation loop tick. Defaults to `false`. * **autoclear** (boolean) - If `true`, the canvas is cleared at the start of each render cycle using `context.clearRect`. Defaults to `true`. * **layerEvents** (boolean) - If `true`, enables event handling on child `Layer` components. Disabled by default due to potential performance impact. * **contextSettings** (CanvasRenderingContext2DSettings | undefined) - An object containing settings to be passed to `canvas.getContext('2d')`. ### Properties * **canvas** (HTMLCanvasElement) - A reference to the underlying canvas DOM element. * **context** (CanvasRenderingContext2D) - A reference to the 2D rendering context of the canvas. ### Methods * **redraw()**: Forces a re-render of the canvas. ### Component Events * **onresize** - Fires when the canvas is resized or its pixel ratio changes. The event payload is of type `CanvasResizeEvent`: ```typescript type CanvasResizeEvent = { width: number; height: number; pixelRatio: number; }; ``` ### DOM Event Handling DOM event handlers (e.g., `onclick`, `onmousemove`) added to the `Canvas` component are forwarded directly to the canvas DOM element. Events can also be managed at the layer level. ``` -------------------------------- ### Layer Component Usage with Typed Render Function (Svelte) Source: https://github.com/dnass/svelte-canvas/blob/master/src/routes/components/layer/+page.svx Shows how to use the Layer component in Svelte while explicitly typing the render function using the imported 'Render' type from 'svelte-canvas'. This improves code clarity and maintainability by ensuring type safety for the render logic. ```svelte   ``` -------------------------------- ### Manage Multiple Layers with Reordering in svelte-canvas Source: https://context7.com/dnass/svelte-canvas/llms.txt Demonstrates how to manage multiple layers in svelte-canvas. Layers render in DOM order, allowing dynamic reordering using Svelte's keyed each blocks to achieve z-index-like behavior. Clicking a layer brings it to the front. ```svelte {#each circles as circle (circle.id)} bringToFront(circle.id)} /> {/each} ``` -------------------------------- ### Canvas Context Settings Prop Configuration Source: https://github.com/dnass/svelte-canvas/blob/master/src/routes/components/canvas/+page.svx Provides an object for configuring the canvas's 2D rendering context. These settings are passed directly to `canvas.getContext`, allowing customization of rendering behavior like alpha channel transparency. ```typescript contextSettings: CanvasRenderingContext2DSettings | undefined = undefined; ``` ```html ``` -------------------------------- ### Layer Component Usage with Render Function (Svelte) Source: https://github.com/dnass/svelte-canvas/blob/master/src/routes/components/layer/+page.svx Demonstrates how to use the Layer component with a render function in Svelte. The render function, which receives a context object, is triggered when the '$text' store value changes, causing the layer to re-render. This showcases basic Svelte reactivity and canvas drawing. ```svelte ``` -------------------------------- ### Configure Canvas Context Settings (Svelte) Source: https://context7.com/dnass/svelte-canvas/llms.txt Customize the canvas 2D context properties using the `contextSettings` prop. This allows for fine-grained control over rendering behavior, such as transparency and performance optimizations. ```svelte ``` -------------------------------- ### Svelte Autoplay Canvas Animation Source: https://context7.com/dnass/svelte-canvas/llms.txt Demonstrates enabling continuous animation on a Svelte Canvas by setting the `autoplay` prop to true. The `render` function creates an animated circle using the `time` parameter, showing circular motion. ```svelte ``` -------------------------------- ### Access Canvas and Context (Svelte) Source: https://github.com/dnass/svelte-canvas/blob/master/src/routes/upgrading/+page.svx Illustrates how to access the canvas and its rendering context in svelte-canvas v2, replacing the `getCanvas` and `getContext` methods with direct property access (`canvas` and `context`) on the component instance. ```svelte ``` ```svelte ``` -------------------------------- ### Update Canvas Event Handlers (Svelte) Source: https://github.com/dnass/svelte-canvas/blob/master/src/routes/upgrading/+page.svx Demonstrates the change in event handler syntax for the Canvas component in svelte-canvas v2, moving from `on:` prefix to direct prop names and simplifying event payloads. ```svelte console.log("clicked")} on:resize={(e) => console.log(e.detail.width)} /> console.log("clicked")} onresize={(e) => console.log(e.width)} /> ``` -------------------------------- ### Canvas Style Prop Configuration Source: https://github.com/dnass/svelte-canvas/blob/master/src/routes/components/canvas/+page.svx Applies custom CSS styles directly to the canvas element. This allows for fine-grained control over the canvas's visual presentation and integration into the page's styling. ```typescript style: string | null = null; ``` -------------------------------- ### Canvas Height Prop Configuration Source: https://github.com/dnass/svelte-canvas/blob/master/src/routes/components/canvas/+page.svx Configures the height of the canvas element. If not provided, it inherits the height from its parent element, ensuring proper sizing and layout. ```typescript height: number = canvas.parentElement.clientHeight; ``` -------------------------------- ### Access Canvas and Context Imperatively (Svelte) Source: https://context7.com/dnass/svelte-canvas/llms.txt Access the Canvas component's `canvas` and `context` properties for imperative operations. This allows for direct manipulation and triggering redraws, useful for tasks like exporting canvas content as an image. ```svelte ``` -------------------------------- ### Canvas Width Prop Configuration Source: https://github.com/dnass/svelte-canvas/blob/master/src/routes/components/canvas/+page.svx Configures the width of the canvas element. When not explicitly set, it defaults to the width of its parent element. This ensures the canvas responsive behavior within its container. ```typescript width: number = canvas.parentElement.clientWidth; ``` -------------------------------- ### Canvas Pixel Ratio Prop Configuration Source: https://github.com/dnass/svelte-canvas/blob/master/src/routes/components/canvas/+page.svx Determines the pixel density of the canvas. It defaults to the window's device pixel ratio, or 2 if unavailable. Setting it to 'auto' utilizes the canvas-size library for optimal rendering across devices, especially beneficial for large canvases on iOS Safari. ```typescript pixelRatio: number | 'auto' = window.devicePixelRatio ?? 2; ``` -------------------------------- ### Canvas Autoplay Prop Configuration Source: https://github.com/dnass/svelte-canvas/blob/master/src/routes/components/canvas/+page.svx Controls whether child layers automatically render on each animation loop tick. When true, rendering is continuous. When false, layers render only when their dependencies change, optimizing performance. ```typescript autoplay: boolean = false; ``` -------------------------------- ### Canvas Rendering Context Property Access Source: https://github.com/dnass/svelte-canvas/blob/master/src/routes/components/canvas/+page.svx Exposes a reference to the canvas's 2D rendering context. This allows direct manipulation of canvas drawing operations and access to context properties and methods. ```typescript context: CanvasRenderingContext2D; ``` ```html ``` -------------------------------- ### Autoplay Mode Source: https://context7.com/dnass/svelte-canvas/llms.txt Enabling autoplay mode on the Canvas component allows for continuous animation loops, driven by animation frames. The `time` parameter in the render function provides a high-resolution timestamp for animation timing. ```APIDOC ## Autoplay Mode ### Description Enable continuous animation by setting the `autoplay` prop on the `Canvas` component. The canvas will re-render on every animation frame, with the `time` parameter in the `render` function providing milliseconds since initialization. ### Usage Example ```svelte ``` ``` -------------------------------- ### Canvas Class Prop Configuration Source: https://github.com/dnass/svelte-canvas/blob/master/src/routes/components/canvas/+page.svx Assigns CSS classes to the canvas element, enabling styling through external stylesheets. It supports single class names or Svelte's ClassValue for more complex class management. ```typescript class: ClassValue | null = null; ``` -------------------------------- ### Layer Props: Render Function Signature (TypeScript) Source: https://github.com/dnass/svelte-canvas/blob/master/src/routes/components/layer/+page.svx Defines the TypeScript signature for the 'render' prop of the Layer component. It specifies the properties available within the render function's props object, including the 2D rendering context, canvas dimensions, and elapsed time. ```typescript render: (props: { context: CanvasRenderingContext2D; width: number; height: number; time: number; }): void; ``` -------------------------------- ### Layer Component Event Handler with Typed Event (Svelte) Source: https://github.com/dnass/svelte-canvas/blob/master/src/routes/components/layer/+page.svx Demonstrates how to define and use a typed event handler for a Layer component in Svelte. The `handleClick` function is typed with `LayerEvent`, providing type safety for accessing event properties like `e.x` and `e.y`. ```svelte   ``` -------------------------------- ### Canvas Component API Source: https://context7.com/dnass/svelte-canvas/llms.txt The Canvas component serves as the primary container for canvas rendering. It manages the HTML5 canvas element, context, sizing, and event handling. It accepts various props to control its behavior and appearance. ```APIDOC ## Canvas Component ### Description The Canvas component creates and manages an HTML5 canvas element with reactive properties. It handles context initialization, sizing, pixel ratio management, and provides a container for Layer components. ### Props - **width** (number) - Optional - The width of the canvas. - **height** (number) - Optional - The height of the canvas. - **pixelRatio** (number | "auto") - Optional - Sets the pixel ratio for high-DPI displays. Defaults to 'auto'. - **autoplay** (boolean) - Optional - Enables continuous animation on every animation frame. Defaults to false. - **autoclear** (boolean) - Optional - Automatically clears the canvas before each render. Defaults to true. - **layerEvents** (boolean) - Optional - Enables layer-level event detection. Defaults to false. - **style** (string) - Optional - Inline styles for the canvas element. - **class** (string) - Optional - CSS classes for the canvas element. ### Events - **onresize** - A callback function that is triggered when the canvas is resized. It receives an object with `width`, `height`, and `pixelRatio`. ### Usage Example ```svelte ``` ``` -------------------------------- ### Canvas Layer Events Prop Configuration Source: https://github.com/dnass/svelte-canvas/blob/master/src/routes/components/canvas/+page.svx Enables event handling for child `Layer` components. This feature is disabled by default due to potential performance impacts, but can be enabled for interactive layer elements. ```typescript layerEvents: boolean = false; ``` -------------------------------- ### Canvas Resize Event Detail Type (TypeScript) Source: https://context7.com/dnass/svelte-canvas/llms.txt Defines the `CanvasResizeEvent` type for the `on:resize` callback on the Svelte Canvas component. The `detail` object provides the new `width`, `height`, and `pixelRatio` of the canvas. ```typescript import type { CanvasResizeEvent } from 'svelte-canvas'; const handleCanvasResize = (detail: CanvasResizeEvent) => { // detail.width: number - new logical width // detail.height: number - new logical height // detail.pixelRatio: number - current pixel ratio console.log(`Resized to ${detail.width}×${detail.height} @ ${detail.pixelRatio}x`); }; ``` -------------------------------- ### Canvas Autoclear Prop Configuration Source: https://github.com/dnass/svelte-canvas/blob/master/src/routes/components/canvas/+page.svx Determines if the canvas is cleared at the beginning of each render cycle. When true, `context.clearRect` is used for a clean slate. This is enabled by default for predictable rendering. ```typescript autoclear: boolean = true; ``` -------------------------------- ### Canvas Element Property Access Source: https://github.com/dnass/svelte-canvas/blob/master/src/routes/components/canvas/+page.svx Provides a direct reference to the underlying HTML canvas DOM element. This property is useful for imperative access to canvas functionalities not exposed through Svelte bindings. ```typescript canvas: HTMLCanvasElement; ``` ```html ``` -------------------------------- ### Simplify Render Function Reactivity (TypeScript) Source: https://github.com/dnass/svelte-canvas/blob/master/src/routes/upgrading/+page.svx Explains the simplification of render function declarations in svelte-canvas v2. Render functions no longer require reactive declarations (`$:`) and can be declared directly with `const`, removing the need for the `$derived` rune. ```typescript // Before let render: Render; $: render = ({ context }) => { ... }; ``` ```typescript // After const render: Render = ({ context }) => { ... }; ``` -------------------------------- ### Canvas Redraw Method Source: https://github.com/dnass/svelte-canvas/blob/master/src/routes/components/canvas/+page.svx Manually triggers a re-render of the canvas content. This method is useful when changes occur outside of Svelte's reactive system that require updating the canvas display. ```typescript redraw(): void; ``` ```html ``` -------------------------------- ### Update Layer Event Handlers (Svelte) Source: https://github.com/dnass/svelte-canvas/blob/master/src/routes/upgrading/+page.svx Shows the updated syntax for Layer component event handlers in svelte-canvas v2. Event callbacks now receive plain objects instead of `CustomEvent`s, and the payload type is renamed from `CanvasLayerEvent` to `LayerEvent`. ```svelte ``` ```svelte ``` -------------------------------- ### Layer Event Detail Type (TypeScript) Source: https://context7.com/dnass/svelte-canvas/llms.txt Defines the `LayerEvent` type for event handlers within Svelte Canvas layers. The `detail` object includes canvas-relative coordinates (`x`, `y`) and the original DOM `originalEvent`. ```typescript import type { LayerEvent } from 'svelte-canvas'; const handleLayerClick = (detail: LayerEvent) => { // detail.x: number - canvas-relative x coordinate // detail.y: number - canvas-relative y coordinate // detail.originalEvent: MouseEvent | TouchEvent - original DOM event console.log(`Clicked at (${detail.x}, ${detail.y})`); detail.originalEvent.preventDefault(); }; ``` -------------------------------- ### LayerEvent Type Definition (TypeScript) Source: https://github.com/dnass/svelte-canvas/blob/master/src/routes/components/layer/+page.svx Defines the TypeScript type for 'LayerEvent', which is passed to event handlers attached to Layer components. It includes the event coordinates (x, y) relative to the canvas and the original DOM event object. ```typescript type LayerEvent = { x: number; y: number; originalEvent: MouseEvent | TouchEvent; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.