### Brush Configuration Example Source: https://github.com/antfu/drauu/blob/main/_autodocs/types.md Example of how to define and apply a Brush configuration object to Drauu. Demonstrates setting brush properties and updating them. ```typescript const brush: Brush = { mode: 'rectangle', color: '#FF0000', size: 2, fill: '#FF000033', cornerRadius: 5 } drauu.brush = brush drauu.brush.color = '#0000FF' ``` -------------------------------- ### Drauu Constructor Example Source: https://github.com/antfu/drauu/blob/main/_autodocs/types.md Example of creating a new Drauu instance with custom options, including brush color, size, input types, scaling, and offset. ```typescript const options: Options = { el: '#svg', brush: { mode: 'line', color: '#0000FF', size: 2 }, acceptsInputTypes: ['pen'], // Only accept stylus input coordinateScale: 2, // Scale coordinates 2x offset: { x: 10, y: 20 } // Offset by 10,20 } const drauu = new Drauu(options) ``` -------------------------------- ### Simple Drauu Setup Source: https://github.com/antfu/drauu/blob/main/_autodocs/configuration.md Basic initialization of Drauu with a target SVG element and default brush settings. ```javascript import { createDrauu } from 'drauu' const drauu = createDrauu({ el: '#svg', brush: { color: 'black', size: 3 } }) ``` -------------------------------- ### Point Example Source: https://github.com/antfu/drauu/blob/main/_autodocs/types.md Example of creating a Point object with coordinates and pressure. Used in event handlers for drawing actions. ```typescript const point: Point = { x: 100, y: 150, pressure: 0.8 } ``` -------------------------------- ### Install Drauu Package Source: https://github.com/antfu/drauu/blob/main/README.md Install the Drauu package using npm. This command is used to add the library to your project dependencies. ```bash npm i drauu ``` -------------------------------- ### Quick Lookup - By Use Case Source: https://github.com/antfu/drauu/blob/main/_autodocs/api-reference/index.md Provides a quick lookup guide to relevant documentation sections based on common user use cases. ```APIDOC ## Quick Lookup ### By Use Case **I want to:** - [Start drawing](../usage-examples.md#basic-setup) → Basic Setup - [Switch drawing modes](../usage-examples.md#mode-switching) → Mode Switching - [Customize the brush](../usage-examples.md#brush-customization) → Brush Customization - [Implement undo/redo](../usage-examples.md#undoredo) → Undo/Redo - [Save and load drawings](../usage-examples.md#save-and-load) → Save and Load - [Handle events](../usage-examples.md#event-handling) → Event Handling - [Configure coordinates](../coordinate-system.md) → Coordinate System - [Debug the system](../event-system.md#debugging-events) → Debugging Events ``` -------------------------------- ### 'start' Event Source: https://github.com/antfu/drauu/blob/main/_autodocs/event-system.md Emitted when a pointer down event begins a new stroke. Fires after pointerdown event and input validation. ```APIDOC ## 'start' Event Emitted when a pointer down event begins a new stroke. ```typescript on('start', () => void): () => void ``` **When:** Immediately after pointerdown event, after input validation passes **State at event time:** - `drauu.drawing` is true - `drauu.model.event` is the PointerEvent - `drauu.model.point` is the starting point - The drawing has NOT been committed yet **Example:** ```javascript drauu.on('start', () => { console.log('Started stroke at:', drauu.model.point) highlightCanvas() }) ``` ``` -------------------------------- ### Listen for Stroke Start Source: https://github.com/antfu/drauu/blob/main/_autodocs/event-system.md Use the 'start' event to execute code immediately after a pointerdown event initiates a new stroke, provided input validation passes. This event is useful for actions like highlighting the canvas. ```typescript drauu.on('start', () => { console.log('Started stroke at:', drauu.model.point) highlightCanvas() }) ``` -------------------------------- ### Common Drauu Configuration Examples Source: https://github.com/antfu/drauu/blob/main/_autodocs/types.md Illustrates common Drauu configurations for specific scenarios like scaled SVGs, older Chrome versions, and touch-only devices. ```typescript // For a scaled/zoomed SVG container const scaled = { el: '#svg', coordinateScale: 2, coordinateTransform: true } // For older Chrome versions with CSS zoom const oldChrome = { el: '#svg', cssZoom: document.documentElement.style.zoom } // For touch-only devices (e.g., tablet) const touchOnly = { el: '#svg', acceptsInputTypes: ['touch', 'pen'] } ``` -------------------------------- ### Custom Operation Example Source: https://github.com/antfu/drauu/blob/main/_autodocs/types.md Example of creating a custom Operation object to handle multi-element changes, defining how to undo and redo the changes. ```typescript // Custom operation for multi-element changes const operation: Operation = { undo() { element1.remove() element2.remove() }, redo() { svg.appendChild(element1) svg.appendChild(element2) } } // Returned from DrawModel.onEnd() return operation ``` -------------------------------- ### Drauu Event Listener Example Source: https://github.com/antfu/drauu/blob/main/_autodocs/types.md Example of registering event listeners with Drauu using the .on() method to handle drawing events and update UI or save progress. ```typescript drauu.on('start', () => console.log('Stroke started')) drauu.on('committed', (node) => console.log('Committed element:', node)) drauu.on('changed', () => saveAutomatically()) drauu.on('end', () => updateUI()) ``` -------------------------------- ### Drauu Diagram Editor Setup Source: https://github.com/antfu/drauu/blob/main/_autodocs/configuration.md Initialize Drauu as a diagram editor, setting the default mode to 'rectangle' and configuring input types. It also demonstrates dynamically changing the mode and brush after an event. ```javascript const drauu = createDrauu({ el: '#shapes', brush: { mode: 'rectangle', color: '#0066FF', size: 1, fill: '#0066FF20', cornerRadius: 3 }, acceptsInputTypes: ['mouse', 'pen'] }) // Add arrow mode drauu.on('committed', () => { drauu.mode = 'line' drauu.brush.arrowEnd = true drauu.brush.color = '#0066FF' }) ``` -------------------------------- ### HTML SVG Element Setup Source: https://github.com/antfu/drauu/blob/main/README.md Include an SVG element in your HTML with a unique ID. This element will serve as the canvas for the Drauu drawing tool. ```html ``` -------------------------------- ### Listener with State and Interval Source: https://github.com/antfu/drauu/blob/main/_autodocs/event-system.md Attach a listener that manages its own state and executes an action only after a certain interval has passed since the last execution. This example debounces saving operations. ```javascript let lastSaveTime = Date.now() const SAVE_INTERVAL = 5000 drauu.on('changed', () => { const now = Date.now() if (now - lastSaveTime > SAVE_INTERVAL) { saveToDB() lastSaveTime = now } }) ``` -------------------------------- ### Verify Coordinate System with Debug Point Source: https://github.com/antfu/drauu/blob/main/_autodocs/coordinate-system.md Add a visual debug point to verify the coordinate system during drawing. Logs the starting SVG coordinates. ```javascript // Add visual debug point drauu.on('start', () => { const point = drauu.model.point const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle') circle.setAttribute('cx', point.x) circle.setAttribute('cy', point.y) circle.setAttribute('r', '5') circle.setAttribute('fill', 'red') drauu.el.appendChild(circle) console.log('Start point (SVG coords):', point) }) ``` -------------------------------- ### Selective Event Listening Source: https://github.com/antfu/drauu/blob/main/_autodocs/event-system.md Demonstrates the importance of listening only to necessary events. It shows a good practice of listening only to 'committed' for saving, and comments out an example of listening to 'changed' which would be too frequent. ```javascript // Good: Only listen to committed strokes drauu.on('committed', (node) => { saveToDatabase(node) }) // Avoid: Listening to 'changed' for every single movement // drauu.on('changed', () => { // // This fires hundreds of times during a single stroke // }) ``` -------------------------------- ### EventsMap Source: https://github.com/antfu/drauu/blob/main/_autodocs/types.md Event callback signatures for the Drauu event system. This defines the types for events emitted by Drauu, such as stroke start, end, commit, and changes. ```APIDOC ## EventsMap ### Description Event callback signatures for the Drauu event system. This defines the types for events emitted by Drauu, such as stroke start, end, commit, and changes. ### Events - **start**: `() => void` - Emitted when a pointer down event begins a stroke. - **end**: `() => void` - Emitted when a pointer up event ends a stroke. - **committed**: `(node: SVGElement | undefined) => void` - Emitted when an operation is committed to the undo stack. - **canceled**: `() => void` - Emitted when a stroke is canceled without committing. - **changed**: `() => void` - Emitted on any drawing change (draw, undo, redo, clear). - **mounted**: `() => void` - Emitted when the `mount()` operation completes. - **unmounted**: `() => void` - Emitted when the `unmount()` operation completes. ### Example ```typescript drauu.on('start', () => console.log('Stroke started')) drauu.on('committed', (node) => console.log('Committed element:', node)) drauu.on('changed', () => saveAutomatically()) drauu.on('end', () => updateUI()) ``` ``` -------------------------------- ### Configure Multi-Touch and Stylus Input Source: https://github.com/antfu/drauu/blob/main/_autodocs/usage-examples.md Sets up Drauu to accept both 'touch' and 'pen' inputs, excluding mouse input. It also includes an event listener to log the detected input type upon drawing start. ```javascript const drauu = createDrauu({ el: '#canvas', acceptsInputTypes: ['touch', 'pen'], // Touch + stylus, no mouse brush: { mode: 'stylus', color: '#000000', size: 3 } }) // Detect input type drauu.on('start', () => { const lastEvent = drauu.model.event console.log('Input type:', lastEvent.pointerType) // 'pen', 'touch', or 'mouse' }) ``` -------------------------------- ### Send Committed Strokes to Server Source: https://github.com/antfu/drauu/blob/main/_autodocs/event-system.md Send drawing data to a server whenever a stroke is committed. This example uses fetch to POST the SVG data. It also includes an optional listener for 'changed' events to update a remote preview in real-time. ```javascript drauu.on('committed', (node) => { const svg = drauu.dump() // Send to server/other clients fetch('/api/drawing', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ svg }) }) }) drauu.on('changed', () => { // Optional: Update preview in real-time updateRemotePreview() }) ``` -------------------------------- ### Listen to Drawing Events Source: https://github.com/antfu/drauu/blob/main/_autodocs/usage-examples.md Subscribe to various Drauu events like 'start', 'move', 'committed', 'canceled', 'changed', and 'end' to trigger side effects such as updating UI, broadcasting changes, or logging actions. ```javascript drauu.on('start', () => { console.log('Started drawing') document.body.classList.add('drawing') }) drauu.on('move', () => { // Real-time feedback updatePreview() }) drauu.on('committed', (element) => { console.log('Stroke committed:', element) broadcastToOtherUsers(drauu.dump()) }) drauu.on('canceled', () => { console.log('Stroke canceled') }) drauu.on('changed', () => { console.log('Drawing modified') autoSaveDrawing() }) drauu.on('end', () => { console.log('Finished drawing') document.body.classList.remove('drawing') }) ``` -------------------------------- ### Drauu Constructor and Factory Function Source: https://github.com/antfu/drauu/blob/main/_autodocs/README.md Shows how to instantiate the Drauu class using either the constructor or the createDrauu factory function, both accepting optional configuration options. ```javascript // new Drauu(options?): Drauu // createDrauu(options?): Drauu ``` -------------------------------- ### Create Drauu Instance with Configuration Source: https://github.com/antfu/drauu/blob/main/_autodocs/configuration.md Configure Drauu during instance creation using the Options interface. This sets up the drawing surface, brush properties, and accepted input types. ```javascript import { createDrauu } from 'drauu' const drauu = createDrauu({ el: '#my-svg', brush: { mode: 'stylus', color: '#000000', size: 3 }, coordinateScale: 1, acceptsInputTypes: ['mouse', 'touch', 'pen'] }) ``` ```javascript const drauu = new Drauu({ el: '#my-svg', brush: { ... } }) ``` -------------------------------- ### getSymbol Source: https://github.com/antfu/drauu/blob/main/_autodocs/api-reference/utility-functions.md Gets the sign of a number (-1 or 1). ```APIDOC ## getSymbol(a) ### Description Gets the sign of a number (-1 or 1). ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method None (Function Signature) ### Endpoint None (Function Signature) ### Parameters - **a** (number) - Required - Number to check ### Returns -1 if negative, 1 otherwise ### Example ```typescript import { getSymbol } from '@drauu/core' getSymbol(-5) // -1 getSymbol(10) // 1 getSymbol(0) // 1 ``` ``` -------------------------------- ### Importing Core API from 'drauu' Source: https://github.com/antfu/drauu/blob/main/_autodocs/api-reference/index.md Recommended way to import all public API elements from the main 'drauu' package. ```javascript import { Drauu, createDrauu, DrawModel, StylusModel, LineModel, RectModel, EllipseModel, EraserModel, simplify, guid, numSort, splitNum, getSymbol, createArrowHead } from 'drauu' ``` -------------------------------- ### guid Source: https://github.com/antfu/drauu/blob/main/_autodocs/api-reference/utility-functions.md Generates a random UUID-like string for unique identifiers. ```APIDOC ## guid() ### Description Generates a random UUID-like string for unique identifiers. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method None (Function Signature) ### Endpoint None (Function Signature) ### Returns Random hex string identifier in the format: `XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX` ### Example ```typescript import { guid } from '@drauu/core' const id = guid() // Result: "a1b2c3d4-e5f6-7890-abcd-ef1234567890" ``` ``` -------------------------------- ### Get Screen Coordinates from PointerEvent Source: https://github.com/antfu/drauu/blob/main/_autodocs/coordinate-system.md Extracts the screen X and Y coordinates from a browser PointerEvent. ```javascript // From PointerEvent const screenX = event.clientX const screenY = event.clientY ``` -------------------------------- ### Create Drauu Instance Source: https://github.com/antfu/drauu/blob/main/_autodocs/README.md Initializes the Drauu drawing library with a target element and basic brush settings. Ensure the target element exists in the DOM. ```javascript import { createDrauu } from 'drauu' const drauu = createDrauu({ el: '#canvas', brush: { color: 'black', size: 3 } }) ``` -------------------------------- ### Configure Initial Brush Settings Source: https://github.com/antfu/drauu/blob/main/_autodocs/configuration.md Set the initial appearance of the brush when creating a Drauu instance. This includes color, size, mode, and fill. ```javascript const drauu = createDrauu({ el: '#svg', brush: { mode: 'rectangle', color: '#FF0000', size: 2, fill: '#FF000033', cornerRadius: 5 } }) ``` -------------------------------- ### Importing Core API from '@drauu/core' Source: https://github.com/antfu/drauu/blob/main/_autodocs/api-reference/index.md Alternative import path for the core API directly from the '@drauu/core' package. ```javascript import { Drauu, createDrauu, DrawModel, StylusModel, LineModel, RectModel, EllipseModel, EraserModel, simplify, guid, numSort, splitNum, getSymbol, createArrowHead } from '@drauu/core' ``` -------------------------------- ### Get Sign of a Number Source: https://github.com/antfu/drauu/blob/main/_autodocs/api-reference/utility-functions.md Returns the sign of a number, -1 for negative and 1 for non-negative. A helper function used by splitNum. ```typescript export function getSymbol(a: number): number ``` ```typescript import { getSymbol } from '@drauu/core' getSymbol(-5) // -1 getSymbol(10) // 1 getSymbol(0) // 1 ``` -------------------------------- ### Main Entry Points Source: https://github.com/antfu/drauu/blob/main/_autodocs/api-reference/index.md The primary way to import and use the Drauu library. Both 'drauu' and '@drauu/core' packages export the same API. ```APIDOC ## Main Entry Points ### Import Paths ```javascript // Main package (recommended) import { createDrauu, Drauu, ... } from 'drauu' // Core package (same exports) import { createDrauu, Drauu, ... } from '@drauu/core' ``` Both packages export the same API. The main `drauu` package re-exports from `@drauu/core`. ``` -------------------------------- ### Get Mouse Position with getMousePosition() Source: https://github.com/antfu/drauu/blob/main/_autodocs/coordinate-system.md Use the getMousePosition() method from the BaseModel class for direct conversion of pointer events to SVG coordinates. ```javascript // Inside a model or with direct access const point = drauu.model.getMousePosition(pointerEvent) console.log(point) // { x: 100, y: 200, pressure: 0.8 } ``` -------------------------------- ### Initialize Drauu Drawing Tool Source: https://github.com/antfu/drauu/blob/main/README.md Import and create a Drauu instance, targeting the SVG element. Configure initial brush properties like mode, color, and size. ```javascript import { createDrauu } from 'drauu' const drauu = createDrauu({ el: '#svg', brush: { mode: 'stylus', // 'line', 'rectangle', 'ellipse' color: 'skyblue', size: 5, } }) // change brush color drauu.options.brush.color = 'red' ``` -------------------------------- ### Import Core and Drauu Source: https://github.com/antfu/drauu/blob/main/_autodocs/overview.md Import the createDrauu factory function and the Drauu class from the 'drauu' package. This is the main entry point for using Drauu. ```javascript import { createDrauu, Drauu } from 'drauu' ``` -------------------------------- ### Create Drauu Instance Source: https://github.com/antfu/drauu/blob/main/_autodocs/api-reference/drauu-class.md Use this convenience function to create a new Drauu instance. Pass a configuration object to customize its behavior, such as the target element and brush settings. ```javascript import { createDrauu } from 'drauu' const drauu = createDrauu({ el: '#svg', brush: { mode: 'line', color: 'blue', size: 2 } }) ``` -------------------------------- ### Detect Stylus Input in Touchmove Event Source: https://github.com/antfu/drauu/blob/main/_autodocs/types.md Example of how to check the `touchType` property within a `touchmove` event handler to detect if the input is from an Apple Pencil or stylus. ```typescript // In touchmove event handler const touch = event.touches[0] if (touch.touchType === 'stylus') { console.log('Apple Pencil detected') } ``` -------------------------------- ### Initialize Draw Mode and Brush Source: https://github.com/antfu/drauu/blob/main/_autodocs/api-reference/drawing-models.md Sets the drawing mode to 'draw', configures brush color and size, and prepares for user input. The path is smoothed upon pointer release. ```javascript drauu.mode = 'draw' drauu.brush.color = '#FF0000' drauu.brush.size = 3 // User draws on canvas // Path is smoothed on pointer up ``` -------------------------------- ### Runtime Drauu Configuration Changes Source: https://github.com/antfu/drauu/blob/main/_autodocs/configuration.md Demonstrates how to modify Drauu's configuration options after the instance has been created, including brush properties, coordinate settings, and input types. ```javascript const drauu = createDrauu({ el: '#svg' }) // Change brush drauu.brush.color = '#FF0000' drauu.brush.size = 5 // Change coordinate settings drauu.options.coordinateScale = 2 drauu.options.offset = { x: 10, y: 20 } // Change input filter drauu.options.acceptsInputTypes = ['pen', 'touch'] ``` -------------------------------- ### Drauu EventsMap Interface Source: https://github.com/antfu/drauu/blob/main/_autodocs/types.md Defines the event callback signatures for the Drauu event system. Use these to listen for drawing events like stroke start, end, and changes. ```typescript interface EventsMap { start: () => void end: () => void committed: (node: SVGElement | undefined) => void canceled: () => void changed: () => void mounted: () => void unmounted: () => void } ``` -------------------------------- ### Brush Interface Definition Source: https://github.com/antfu/drauu/blob/main/_autodocs/types.md Defines the configuration for stroke appearance and behavior, including color, size, fill, and mode. Used for setting and getting the current brush properties. ```typescript interface Brush { mode?: DrawingMode color: string size: number fill?: string dasharray?: string cornerRadius?: number arrowEnd?: boolean stylusOptions?: StrokeOptions } ``` -------------------------------- ### File Organization Structure Source: https://github.com/antfu/drauu/blob/main/_autodocs/README.md Illustrates the directory structure of the Drauu project, showing the location of the main README, overview, configuration, API reference, and other documentation files. ```text output/ ├── README.md (this file) ├── overview.md ├── types.md ├── configuration.md ├── coordinate-system.md ├── event-system.md ├── usage-examples.md └── api-reference/ ├── index.md ├── drauu-class.md ├── drawing-models.md └── utility-functions.md ``` -------------------------------- ### Line Model Configuration Source: https://github.com/antfu/drauu/blob/main/_autodocs/api-reference/drawing-models.md Set up the line drawing mode to create straight lines with options for arrow ends. Customize color, size, and enable arrow markers. ```javascript drauu.mode = 'line' drauu.brush.color = 'blue' drauu.brush.size = 2 drauu.brush.arrowEnd = true // User clicks and drags to draw line with arrow // Hold Shift to constrain to 45° angles // Hold Alt to draw from center point ``` -------------------------------- ### Debounce High-Frequency 'changed' Events Source: https://github.com/antfu/drauu/blob/main/_autodocs/event-system.md Debounce the 'changed' event to avoid executing expensive operations too frequently during rapid drawing. This example ensures the operation runs at most once every 100ms. ```javascript let debounceTimer drauu.on('changed', () => { clearTimeout(debounceTimer) debounceTimer = setTimeout(() => { // This runs at most once per 100ms expensiveOperation() }, 100) }) ``` -------------------------------- ### Unmount and Cleanup Drauu Source: https://github.com/antfu/drauu/blob/main/_autodocs/usage-examples.md Demonstrates how to unmount Drauu, listen for the unmounted event, and perform cleanup by removing the element from the DOM. ```javascript drauu.on('unmounted', () => { console.log('Drawing unmounted') // Clean up resources }) // Before removing from DOM drauu.unmount() drauu.el.remove() ``` -------------------------------- ### Initialize Drauu with SVG Element Source: https://github.com/antfu/drauu/blob/main/_autodocs/usage-examples.md Create a minimal drawing application by initializing Drauu with a programmatically created SVG element. Ensure the SVG element is appended to the DOM before initialization. ```javascript import { createDrauu } from 'drauu' // Create SVG element const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg') svg.setAttribute('width', '800') svg.setAttribute('height', '600') document.body.appendChild(svg) // Initialize Drauu const drauu = createDrauu({ el: svg, brush: { mode: 'stylus', color: 'black', size: 3 } }) ``` -------------------------------- ### Intercept Drawing Events for Custom Logic Source: https://github.com/antfu/drauu/blob/main/_autodocs/usage-examples.md Attaches event listeners to 'start' and 'committed' events to execute custom logic. This allows for pre-drawing actions or post-commit modifications to drawing elements. ```javascript drauu.on('start', () => { // Custom logic before drawing starts if (drauu.mode === 'line') { console.log('Drawing a line') } }) drauu.on('committed', (node) => { // Custom logic after element committed if (node) { node.classList.add('new-element') node.dataset.timestamp = Date.now() } }) ``` -------------------------------- ### Constructor Source: https://github.com/antfu/drauu/blob/main/_autodocs/api-reference/drauu-class.md Creates a new Drauu instance. It can be configured with options for the brush, target element, and coordinate handling. If an `el` option is provided, it automatically mounts to the target SVG element. ```APIDOC ## new Drauu(options?) ### Description Creates a new Drauu instance. If an `el` option is provided, automatically mounts to the target SVG element. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | options | [Options](/output/types.md#options) | No | {} | Configuration object for brush, target element, and coordinate handling | ### Request Example ```javascript import { Drauu } from 'drauu' const drauu = new Drauu({ el: '#svg', brush: { mode: 'stylus', color: 'black', size: 3 } }) ``` ``` -------------------------------- ### Log Transformation Steps for Debugging Source: https://github.com/antfu/drauu/blob/main/_autodocs/coordinate-system.md Log detailed transformation steps, including screen coordinates, CSS zoom, offset, and scale, to help debug coordinate mapping issues. ```javascript function debugTransformation(event) { console.log('Screen:', { x: event.clientX, y: event.clientY }) const cssZoom = drauu.options.cssZoom ?? 1 console.log('CSS Zoom:', cssZoom) const offset = drauu.options.offset ?? { x: 0, y: 0 } console.log('Offset:', offset) const scale = drauu.options.coordinateScale ?? 1 console.log('Scale:', scale) const point = drauu.model.getMousePosition(event) console.log('Final SVG:', point) } drauu.model.addEventListener('pointermove', debugTransformation, true) ``` -------------------------------- ### Unsubscribe from Drauu Events on Component Unmount Source: https://github.com/antfu/drauu/blob/main/_autodocs/event-system.md This example demonstrates the correct way to unsubscribe from Drauu events when a component unmounts in React or Vue to prevent memory leaks. Ensure the unsubscribe function is called in the `beforeUnmount` lifecycle hook. ```javascript // React/Vue example const component = { mounted() { this.unsubscribe = drauu.on('changed', this.handleChange) }, beforeUnmount() { this.unsubscribe() } } ``` -------------------------------- ### Classes and Factories Source: https://github.com/antfu/drauu/blob/main/_autodocs/api-reference/index.md Lists the main classes and factory functions available in the Drauu library, along with their types, locations, and a brief description. ```APIDOC ## Classes and Factories | Export | Type | Location | Description | |---|---|---|---| | Drauu | class | packages/core/src/drauu.ts:5 | Main drawing manager class | | createDrauu(options?) | function | packages/core/src/drauu.ts:300 | Factory function to create Drauu instance | | DrawModel | class | packages/core/src/models/draw.ts:7 | Smooth freehand drawing model | | StylusModel | class | packages/core/src/models/stylus.ts:5 | Pressure-sensitive drawing model | | LineModel | class | packages/core/src/models/line.ts:6 | Straight line drawing model | | RectModel | class | packages/core/src/models/rect.ts:5 | Rectangle shape drawing model | | EllipseModel | class | packages/core/src/models/ellipse.ts:5 | Ellipse/circle drawing model | | EraserModel | class | packages/core/src/models/eraser.ts:13 | Eraser path intersection model | | BaseModel | class (abstract) | packages/core/src/models/base.ts:5 | Abstract base for all drawing models | ``` -------------------------------- ### Coordinate Transformation Pipeline Steps Source: https://github.com/antfu/drauu/blob/main/_autodocs/coordinate-system.md Illustrates the sequence of transformations applied to convert screen coordinates to SVG coordinates. ```text PointerEvent (screen coordinates) ↓ Apply CSS Zoom ↓ Apply Offset ↓ Apply SVG CTM Transform (if enabled) ↓ Apply Coordinate Scale ↓ SVG Coordinates (final) ``` -------------------------------- ### Event System Source: https://github.com/antfu/drauu/blob/main/_autodocs/api-reference/index.md APIs for registering event listeners and managing events within Drauu. ```APIDOC ## on(type, fn) ### Description Registers an event listener for a specific event type. ### Method `on(type, fn)` ### Endpoint N/A (Method on Drauu instance) ### Parameters - **type** (keyof EventsMap) - Required - The type of event to listen for. - **fn** (fn) - Required - The callback function to execute when the event is triggered. ### Request Example ```javascript drauu.on('drawEnd', (data) => { console.log('Drawing ended:', data) }) ``` ### Response None ``` -------------------------------- ### Import Paths for Drauu Source: https://github.com/antfu/drauu/blob/main/_autodocs/api-reference/index.md Import the Drauu library using either the main package or the core package. Both export the same API, with the main package re-exporting from the core. ```javascript import { createDrauu, Drauu, ... } from 'drauu' ``` ```javascript import { createDrauu, Drauu, ... } from '@drauu/core' ``` -------------------------------- ### Options Source: https://github.com/antfu/drauu/blob/main/_autodocs/types.md Configuration object for creating a Drauu instance. It allows customization of the SVG element, brush properties, input types, coordinate system, and more. ```APIDOC ## Options ### Description Configuration object for creating a Drauu instance. It allows customization of the SVG element, brush properties, input types, coordinate system, and more. ### Properties - **el** (string | SVGSVGElement) - Optional - SVG element or CSS selector to mount to. - **brush** (Brush) - Optional - Initial brush configuration. Defaults to `{ color: 'black', size: 3, mode: 'stylus' }`. - **acceptsInputTypes** (('mouse' | 'touch' | 'pen')[]) - Optional - Pointer event types to accept. Defaults to `['mouse', 'touch', 'pen']`. - **eventTarget** (string | Element) - Optional - Element to listen for pointer events. Defaults to the same as `el`. - **window** (Window) - Optional - Window object to listen for pointer events. Defaults to the global `window`. - **coordinateScale** (number) - Optional - Scale factor for all coordinates. Defaults to `1`. - **coordinateTransform** (boolean) - Optional - Apply SVG CTM inverse transform to coordinates. Defaults to `true`. - **cssZoom** (number) - Optional - CSS zoom level of the page. Defaults to `1`. - **offset** ({ x: number, y: number }) - Optional - Offset to apply to all coordinates. Defaults to `{ x: 0, y: 0 }`. ### Coordinate System Computation Order 1. Get clientX/pageX and clientY/pageY from PointerEvent. 2. Apply cssZoom: divide by cssZoom value. 3. Apply offset: add offset.x and offset.y. 4. If coordinateTransform is true: apply SVG CTM inverse transform. 5. Apply coordinateScale: multiply by scale. ### Example ```typescript const options = { el: '#svg', brush: { mode: 'line', color: '#0000FF', size: 2 }, acceptsInputTypes: ['pen'], // Only accept stylus input coordinateScale: 2, // Scale coordinates 2x offset: { x: 10, y: 20 } // Offset by 10,20 } const drauu = new Drauu(options) ``` ### Common Configurations ```typescript // For a scaled/zoomed SVG container const scaled = { el: '#svg', coordinateScale: 2, coordinateTransform: true } // For older Chrome versions with CSS zoom const oldChrome = { el: '#svg', cssZoom: document.documentElement.style.zoom } // For touch-only devices (e.g., tablet) const touchOnly = { el: '#svg', acceptsInputTypes: ['touch', 'pen'] } ``` ``` -------------------------------- ### Instantiate Drauu with Options Source: https://github.com/antfu/drauu/blob/main/_autodocs/api-reference/drauu-class.md Creates a new Drauu instance and optionally mounts it to a target SVG element with specific brush configurations. ```typescript constructor(public options: Options = {}) ``` ```javascript import { Drauu } from 'drauu' const drauu = new Drauu({ el: '#svg', brush: { mode: 'stylus', color: 'black', size: 3 } }) ``` -------------------------------- ### Drauu Class Methods Source: https://github.com/antfu/drauu/blob/main/_autodocs/README.md Outlines the essential methods available on the Drauu instance for managing the drawing lifecycle, including mounting, unmounting, event handling, undo/redo, clearing, and exporting. ```javascript // mount(el, eventEl?, window?): void // unmount(): void // on(type, fn): () => void // undo(): boolean // redo(): boolean // canUndo(): boolean // canRedo(): boolean // clear(): void // cancel(): void // dump(): string // load(svg): void ``` -------------------------------- ### Listen for Drauu Mount Completion Source: https://github.com/antfu/drauu/blob/main/_autodocs/event-system.md The 'mounted' event is emitted after `mount()` successfully attaches Drauu to the specified element and sets up event listeners. Use this to enable drawing-related UI elements once Drauu is ready. ```typescript drauu.on('mounted', () => { console.log('Ready to draw') enableDrawingUI() }) drauu.mount('#canvas') ``` -------------------------------- ### Common Tasks Source: https://github.com/antfu/drauu/blob/main/_autodocs/README.md Provides quick code snippets for frequent operations like changing brush color, saving drawings, implementing undo functionality, listening to changes, handling scaled SVGs, and managing multiple drawing modes. ```APIDOC ## Common Tasks ### Change Brush Color ```javascript drauu.brush.color = '#FF0000' ``` ### Save Drawing ```javascript const svg = drauu.dump() localStorage.setItem('drawing', svg) ``` ### Implement Undo Button ```javascript if (drauu.canUndo()) { drauu.undo() } ``` ### Listen to Changes ```javascript drauu.on('changed', () => { updateUI() }) ``` ### Handle Scaled SVG ```javascript const drauu = createDrauu({ el: '#svg', coordinateScale: 2 }) ``` ### Multiple Drawing Modes ```javascript drauu.on('committed', () => { drauu.mode = 'line' // Switch mode after each stroke }) ``` ``` -------------------------------- ### Configure Stylus-Specific Brush Options Source: https://github.com/antfu/drauu/blob/main/_autodocs/configuration.md Customize advanced stylus drawing behavior using `stylusOptions`. This allows fine-tuning of stroke dynamics like thinning and pressure simulation. ```javascript const drauu = createDrauu({ el: '#svg', brush: { mode: 'stylus', color: '#000000', size: 5, stylusOptions: { size: 5, thinning: 0.9, simulatePressure: false, start: { taper: 5 }, end: { taper: 5 }, easing: (t) => t // Linear easing } } }) ``` -------------------------------- ### Documentation Pages Source: https://github.com/antfu/drauu/blob/main/_autodocs/api-reference/index.md Links to various documentation pages covering different aspects of the Drauu project. ```APIDOC ## Documentation Pages | Page | Content | |---|---| | [../overview.md](../overview.md) | Project overview and module structure | | [../types.md](../types.md) | Complete type reference | | [../configuration.md](../configuration.md) | Configuration options and examples | | [../usage-examples.md](../usage-examples.md) | Practical code examples | | [../event-system.md](../event-system.md) | Event types and patterns | | [../coordinate-system.md](../coordinate-system.md) | Coordinate transformation guide | ``` -------------------------------- ### Drauu Options Interface Source: https://github.com/antfu/drauu/blob/main/_autodocs/types.md Defines the configuration options for initializing a Drauu instance. Customize elements, brush properties, input types, and coordinate transformations. ```typescript interface Options { el?: string | SVGSVGElement brush?: Brush acceptsInputTypes?: ('mouse' | 'touch' | 'pen')[] eventTarget?: string | Element window?: Window coordinateScale?: number coordinateTransform?: boolean cssZoom?: number offset?: { x: number, y: number } } ``` -------------------------------- ### Integrate Color Picker Source: https://github.com/antfu/drauu/blob/main/_autodocs/usage-examples.md Connect a color picker input to dynamically update the brush color in Drauu. The selected color is also persisted to local storage upon committing a stroke. ```javascript const colorPicker = document.querySelector('#color-picker') colorPicker.value = '#000000' colorPicker.addEventListener('input', (e) => { drauu.brush.color = e.target.value }) drauu.on('committed', () => { // Auto-save color preference localStorage.setItem('lastColor', drauu.brush.color) }) ``` -------------------------------- ### Constants Source: https://github.com/antfu/drauu/blob/main/_autodocs/api-reference/index.md Lists constants used within the Drauu library, including their values and descriptions. ```APIDOC ## Constants | Export | Value | Location | Description | |---|---|---|---| | DECIMAL | 2 | packages/core/src/utils/index.ts:21 | Decimal precision for SVG coordinates | | D | 2 | packages/core/src/utils/index.ts:23 | Alias for DECIMAL | ``` -------------------------------- ### Configure Window Object for Drauu Events Source: https://github.com/antfu/drauu/blob/main/_autodocs/configuration.md Specify a custom window object for Drauu's pointermove, pointerup, and keyboard events. Useful for iframes, popups, or testing environments. ```typescript window?: Window ``` ```javascript // Listen to events from an iframe const iframe = document.querySelector('iframe') const drauu = createDrauu({ el: '#svg', window: iframe.contentWindow }) // Listen to events from a popup window const popup = window.open(...) const drauu = createDrauu({ el: svg, window: popup }) ``` -------------------------------- ### Utility Functions Source: https://github.com/antfu/drauu/blob/main/_autodocs/api-reference/index.md Lists utility and helper functions available in the Drauu library. These are primarily for internal use but are exported for advanced users. ```APIDOC ## Utility Functions | Export | Location | Description | |---|---|---| | simplify(points, tolerance, highestQuality?) | packages/core/src/utils/simplify.ts:102 | Simplify polyline using Ramer-Douglas-Peucker | | guid() | packages/core/src/utils/index.ts:16 | Generate random UUID-like string | | numSort(a, b) | packages/core/src/utils/index.ts:1 | Sort numbers ascending | | splitNum(a) | packages/core/src/utils/index.ts:11 | Split number into absolute value and sign | | getSymbol(a) | packages/core/src/utils/index.ts:5 | Get sign of a number (-1 or 1) | | createArrowHead(id, fill) | packages/core/src/utils/dom.ts:1 | Create SVG arrow marker definition | ``` -------------------------------- ### Drauu Class API Reference Source: https://github.com/antfu/drauu/blob/main/_autodocs/README.md Reference for the main `Drauu` class, including its constructor, properties, and methods for managing drawing state, history, and events. ```APIDOC ## API Quick Reference ### Class: Drauu **Constructor:** - `new Drauu(options?): Drauu` - `createDrauu(options?): Drauu` **Properties:** - `el: SVGSVGElement | null` - `options: Options` - `drawing: boolean` - `brush: Brush` (getter/setter) - `mode: DrawingMode` (getter/setter) - `mounted: boolean` (getter) **Methods:** - `mount(el, eventEl?, window?): void` - `unmount(): void` - `on(type, fn): () => void` - `undo(): boolean` - `redo(): boolean` - `canUndo(): boolean` - `canRedo(): boolean` - `clear(): void` - `cancel(): void` - `dump(): string` - `load(svg): void` ``` -------------------------------- ### Initialize Drauu with HTML Container Source: https://github.com/antfu/drauu/blob/main/_autodocs/usage-examples.md Integrate Drauu into an existing HTML structure by referencing a container element using a CSS selector. This is useful when the canvas is already defined in your HTML. ```html ``` ```javascript import { createDrauu } from 'drauu' const drauu = createDrauu({ el: '#canvas', brush: { color: 'black', size: 3 } }) ``` -------------------------------- ### mount Source: https://github.com/antfu/drauu/blob/main/_autodocs/api-reference/drauu-class.md Attaches the Drauu instance to an SVG element and sets up event listeners. It can take an SVG element or a CSS selector, and optionally a separate element for event listening and a window object. ```APIDOC ## mount(el, eventEl?, listenWindow?) ### Description Attaches the Drauu instance to an SVG element and sets up event listeners. Does not clear the drawing. ### Method POST ### Endpoint `/mount` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | el | string \| SVGSVGElement | Yes | — | CSS selector string or SVG element reference | | eventEl | string \| Element | No | el | Element to listen for pointer events (default: same as el) | | listenWindow | Window | No | window | Window object to listen for pointermove/pointerup events | ### Throws - Error if already mounted - Error if target element not found - Error if target is not an SVG element - Error if SVG element not created via document.createElementNS() ### Request Example ```javascript const drauu = new Drauu() // Mount to existing SVG element drauu.mount('#my-svg') // Or mount to element reference with separate event target const svg = document.querySelector('svg') const container = document.querySelector('.canvas-container') drauu.mount(svg, container) ``` ``` -------------------------------- ### Interfaces and Types Source: https://github.com/antfu/drauu/blob/main/_autodocs/api-reference/index.md Details the interfaces and type definitions used within the Drauu library, including their purpose and location. ```APIDOC ## Interfaces and Types | Export | Type | Location | Description | |---|---|---|---| | DrawingMode | type | packages/core/src/types.ts:3 | Union type for all drawing modes | | Brush | interface | packages/core/src/types.ts:5 | Brush configuration | | Point | interface | packages/core/src/types.ts:55 | 2D point with optional pressure | | Options | interface | packages/core/src/types.ts:61 | Configuration for Drauu instance | | EventsMap | interface | packages/core/src/types.ts:118 | Event callback signatures | | Operation | interface | packages/core/src/types.ts:128 | Undo/redo operation | | EraserPathFragment | interface | packages/core/src/models/eraser.ts:4 | Eraser path segment for intersection | ``` -------------------------------- ### Configure Stylus-Only Input Mode Source: https://github.com/antfu/drauu/blob/main/_autodocs/usage-examples.md Initializes Drauu to accept only 'pen' input types, effectively enabling stylus-only mode. It also configures stylus-specific pressure sensitivity options. ```javascript const drauu = createDrauu({ el: '#canvas', brush: { mode: 'stylus', color: 'black', size: 5 }, acceptsInputTypes: ['pen'], // Apple Pencil only // Pressure sensitivity options brush: { stylusOptions: { simulatePressure: false, // Use real pressure size: 5, thinning: 0.9, start: { taper: 5 }, end: { taper: 5 } } } }) ``` -------------------------------- ### Drawing Mode Switching Source: https://github.com/antfu/drauu/blob/main/_autodocs/api-reference/drawing-models.md Demonstrates how to switch between different drawing modes in Drauu by assigning values to the `drauu.mode` property. ```javascript // Switch between modes drauu.mode = 'draw' drauu.mode = 'rectangle' drauu.mode = 'eraseLine' ``` -------------------------------- ### Configure Scaled Canvas with Transformation Source: https://github.com/antfu/drauu/blob/main/_autodocs/usage-examples.md Applies a CSS scale transform to the canvas container and configures Drauu with `coordinateScale` and `coordinateTransform` to ensure drawing coordinates match the scaled display. ```javascript const container = document.querySelector('#canvas-container') container.style.transform = 'scale(2)' const drauu = createDrauu({ el: '#canvas', coordinateScale: 2, // Account for scale transform coordinateTransform: true }) ``` -------------------------------- ### Rectangle Model Configuration Source: https://github.com/antfu/drauu/blob/main/_autodocs/api-reference/drawing-models.md Configure the rectangle drawing mode to create rectangles and squares. Set color, fill, stroke size, and corner radius. Supports drawing from the center and proportional squares. ```javascript drauu.mode = 'rectangle' drauu.brush.color = '#FF0000' drauu.brush.fill = '#FF000033' drauu.brush.size = 2 drauu.brush.cornerRadius = 8 // User clicks and drags to draw rectangle // Hold Shift to draw a square // Hold Alt to draw from center point ``` -------------------------------- ### Drawing Mode Selector Source: https://github.com/antfu/drauu/blob/main/_autodocs/api-reference/drawing-models.md Demonstrates how to switch between different drawing modes available in the Drauu library, such as 'draw', 'ellipse', and 'eraseLine'. ```APIDOC ## Drawing Mode Selector All models are instantiated in createModels() and accessed via the Drauu.mode property. **Valid modes:** | Mode | Class | Behavior | |-----------|-------------|------------------------------| | 'draw' | DrawModel | Smooth freehand with Bézier curves | | 'stylus' | StylusModel | Pressure-sensitive stroke | | 'line' | LineModel | Straight line (Shift constrains angle, Alt draws from center) | | 'rectangle' | RectModel | Rectangle shape (Shift makes square, Alt draws from center) | | 'ellipse' | EllipseModel| Ellipse shape (Shift makes circle, Alt draws from center) | | 'eraseLine'| EraserModel | Erase by line intersection | **Example:** ```javascript // Switch between modes drauu.mode = 'draw' drauu.mode = 'rectangle' drauu.mode = 'eraseLine' ``` ``` -------------------------------- ### Stylus Model Configuration Source: https://github.com/antfu/drauu/blob/main/_autodocs/api-reference/drawing-models.md Configure the stylus drawing mode for natural-looking strokes with variable width using perfect-freehand. Adjust color, size, and stylus options like pressure simulation and easing. ```javascript drauu.mode = 'stylus' drauu.brush.color = '#000000' drauu.brush.size = 5 drauu.brush.stylusOptions = { simulatePressure: true, easing: (t) => t } // User draws with stylus/touch pressure // Stroke width varies based on pressure ```