### Install dependencies and run the development studio Source: https://github.com/benjitaylor/drawesome/blob/master/CONTRIBUTING.md Run pnpm install to install dependencies, then pnpm dev to start the studio with every prop wired to a control. The studio consumes the package via a Vite alias pointed at its source, so engine changes hot-reload without a rebuild. ```bash pnpm install pnpm dev # the studio, with every prop wired to a control ``` -------------------------------- ### Run development environment Source: https://github.com/benjitaylor/drawesome/blob/master/tests/README.md Command to start the studio for manual testing of toolbar features. ```sh pnpm dev ``` -------------------------------- ### Quick Start Source: https://github.com/benjitaylor/drawesome/blob/master/README.md Basic usage of the Draw component. Import the component and its styles, then render it inside a container with a defined height. ```APIDOC ## Quick Start ```tsx import { Draw } from 'drawesome' import 'drawesome/styles.css' function Canvas() { return (
) } ``` It fills its parent container. Set a height on the wrapper. ``` -------------------------------- ### Install Drawesome via npm Source: https://github.com/benjitaylor/drawesome/blob/master/README.md Use this command to install the library in your React project. Note that react >=18 is a peer dependency. ```bash npm install drawesome ``` -------------------------------- ### useTooltips Usage Example Source: https://github.com/benjitaylor/drawesome/blob/master/_autodocs/api-reference/tooltip.md Demonstrates how to integrate the useTooltips hook within a custom tray component. ```tsx import { useTooltips } from 'drawesome' // internal — via Toolbar's props instead // Toolbar wires it up internally; for a custom tray you would: function Tray() { const tip = useTooltips({ scope: 'tools' }, 'bottom') return ( <> {tip.node} ) } ``` -------------------------------- ### Quick Start with Draw component Source: https://github.com/benjitaylor/drawesome/blob/master/README.md Import the Draw component and its CSS, then place it within a container with a defined height to initialize the canvas. ```tsx import { Draw } from 'drawesome' import 'drawesome/styles.css' function Canvas() { return (
) } ``` -------------------------------- ### Installation Source: https://github.com/benjitaylor/drawesome/blob/master/README.md Install Drawesome via npm. Requires React 18 or higher as a peer dependency. ```APIDOC ## Install ```bash npm install drawesome ``` Peer dependency: `react >=18`. ``` -------------------------------- ### Basic Draw component implementation Source: https://github.com/benjitaylor/drawesome/blob/master/_autodocs/api-reference/draw.md A basic example showing how to initialize the Draw component with specific tools and disabled controls. ```tsx import { useRef } from 'react' import { Draw, type DrawHandle } from 'drawesome' import 'drawesome/styles.css' function Canvas() { const draw = useRef(null) return (
) } ``` -------------------------------- ### Usage Examples for toSvg and toPng Source: https://github.com/benjitaylor/drawesome/blob/master/_autodocs/api-reference/engine-serialize.md Demonstrates how to serialize strokes to an SVG string and how to export a PNG blob with error handling. ```tsx import { toSvg, toPng } from 'drawesome' // Serialize to SVG text (e.g. to POST to a server, or embed) const svg = toSvg(strokes, 800, 600, '#ffffff') // // Rasterise at 2× device pixels, with error handling async function exportPng() { try { const blob = await toPng(strokes, 800, 600, 'transparent', 2) const url = URL.createObjectURL(blob) const a = document.createElement('a') a.href = url a.download = 'sketch.png' a.click() setTimeout(() => URL.revokeObjectURL(url), 0) } catch (err) { console.error('PNG export failed:', (err as Error).message) } } ``` -------------------------------- ### Run E2E regression tests Source: https://github.com/benjitaylor/drawesome/blob/master/tests/README.md Commands to install dependencies, set up Playwright browsers, and execute the end-to-end test suite. ```sh pnpm install pnpm exec playwright install chromium firefox webkit pnpm test:e2e ``` -------------------------------- ### Usage Example Source: https://github.com/benjitaylor/drawesome/blob/master/_autodocs/api-reference/engine-geometry.md Example usage of the drawesome geometry engine functions for rendering strokes and eraser layers. ```APIDOC ## Usage Example ### Description Example usage of the drawesome geometry engine functions for rendering strokes and eraser layers. ### Functions Used - strokePath - polylinePath - dotRadius - eraseLayers - nextId ### Example ```tsx import { strokePath, polylinePath, dotRadius, eraseLayers, nextId } from 'drawesome' // The visible mark for a committed stroke const d = strokePath('brush', 14, points, true, { taper: 10 }) // d === "" means: render a dot instead if (d === "") { const [x, y] = points[0] return } // Eraser layering — group inks that share eraser passes const layers = eraseLayers(strokes) for (const layer of layers) { const cuts = layer.erasers.map((i) => polylinePath(strokes[i].points)) // …emit with cuts stroked black at strokes[i].size, layer.ink filled on top } ``` ### Notes - No error paths: empty inputs return neutral values ("", [], 0 from the counter before the first stroke). - getSvgPathFromStroke silently skips degenerate rings. ``` -------------------------------- ### Implementing the Toolbar component Source: https://github.com/benjitaylor/drawesome/blob/master/_autodocs/api-reference/toolbar.md This example demonstrates how to integrate the Toolbar and DrawSurface components within a React application. It manages the tool state using useState and connects drawing actions like undo, redo, and clear to the useDrawing hook. ```tsx import { useState } from 'react' import { DrawSurface, Toolbar, useDrawing, PEN_BY_ID, type ToolState } from 'drawesome' function Canvas() { const drawing = useDrawing([]) const [tool, setTool] = useState({ active: 'pen', color: '#111111', size: PEN_BY_ID.pen.defaultSize, opacity: PEN_BY_ID.pen.defaultOpacity, eraserSize: 28, }) return (
tool.color} onSelect={(id) => setTool((t) => ({ ...t, active: id }))} onChange={(p) => setTool((t) => ({ ...t, ...p }))} canUndo={drawing.canUndo} canRedo={drawing.canRedo} onUndo={drawing.undo} onRedo={drawing.redo} onClear={drawing.clear} hasStrokes={drawing.strokes.length > 0} icon={} />
) } ``` -------------------------------- ### Usage examples for ToolIcon Source: https://github.com/benjitaylor/drawesome/blob/master/_autodocs/api-reference/toolicon.md Shows two usage patterns: mapping over a PENS array to render a row of pens with their ink colors, and rendering a single disc icon with a size of 42, studio look, and a badge of 18. The color prop must be a valid CSS color string; invalid colors are not handled. ```tsx import { ToolIcon } from 'drawesome' // A row of pens, each shown in what it would draw ( ))} // The disc icon for a collapsed bar, with the gauge ``` -------------------------------- ### Catching toPng and download errors in TypeScript Source: https://github.com/benjitaylor/drawesome/blob/master/_autodocs/errors.md Shows how to await DrawHandle.download and DrawHandle.toPng inside try/catch blocks. The catch block receives an Error instance whose message is one of the three documented strings: 'Could not rasterise the drawing', 'Could not get a 2D context', or 'Could not encode the PNG'. ```tsx import { Draw, type DrawHandle } from 'drawesome' const draw = useRef(null) async function save() { try { await draw.current?.download('sketch', 'png', 2) } catch (err) { // err instanceof Error — message is one of the three strings above report(`Export failed: ${(err as Error).message}`) } } async function blob() { try { const b = await draw.current?.toPng(3) // … } catch (err) { console.error(err) } } ``` -------------------------------- ### Usage of PENS and PEN_BY_ID Source: https://github.com/benjitaylor/drawesome/blob/master/_autodocs/api-reference/engine-pens.md Shows how to import PENS and PEN_BY_ID, create a tray of pens by mapping over ids, open a pen at its default settings, and generate keyboard shortcuts. Note that PENS is mutable and should be treated as read-only; use props instead of mutating it. ```tsx import { PENS, PEN_BY_ID } from 'drawesome' // The default tray — iterate PENS, or reorder: const tray = ['fountain', 'pencil', 'highlighter'].map((id) => PEN_BY_ID[id as PenId]) // Opening a pen at its default function open(pen: PenId) { const preset = PEN_BY_ID[pen] return { size: preset.defaultSize, opacity: preset.defaultOpacity, color: preset.defaultColor, } } // The seven keyboard shortcuts, per pen const shortcuts = Object.fromEntries(PENS.map((p) => [p.key, p.id])) // { c: 'pencil', p: 'pen', f: 'fineliner', m: 'marker', h: 'highlighter', b: 'brush', g: 'fountain' } ``` -------------------------------- ### Responsive placement and tools Source: https://github.com/benjitaylor/drawesome/blob/master/README.md Adjust the placement and available tools based on screen width using the placement, tools, and controls props. ```tsx ``` -------------------------------- ### MotionPreset / MotionOptions Source: https://github.com/benjitaylor/drawesome/blob/master/_autodocs/api-reference/draw.md MotionPreset defines available motion presets, and MotionOptions configures entrance/exit animations and duration. ```APIDOC ## MotionPreset ### Description Defines available motion presets. ### Values - `"rise"` - Rise animation. - `"none"` - No animation. ## MotionOptions ### Description Configures entrance/exit animations and duration. ### Properties - `in` (MotionPreset) - Optional - Entrance preset. - `out` (MotionPreset) - Optional - Exit preset. - `duration` (number) - Optional - Milliseconds, covers whichever direction is playing. ``` -------------------------------- ### Import Drawesome components and styles Source: https://github.com/benjitaylor/drawesome/blob/master/_autodocs/index.md Basic usage showing how to import the Draw component and the required CSS stylesheet. ```tsx import { Draw } from 'drawesome' import 'drawesome/styles.css' ``` -------------------------------- ### Repository layout structure Source: https://github.com/benjitaylor/drawesome/blob/master/_autodocs/index.md Overview of the monorepo structure, including the core library in packages/draw and the demo harness in apps/studio. ```text packages/draw/ the publishable library ("drawesome") src/index.ts single public entry point (barrel) src/engine/ pure TS stroke engine — no React types.ts Point, PenId, ToolId, Pen, StrokeShape, Stroke, Board pens.ts PENS, PEN_BY_ID freehand.ts getStroke, FreehandOptions geometry.ts strokePath, polylinePath, dotRadius, eraseLayers, nextId, … serialize.ts toSvg, toPng src/hooks/use-drawing.ts useDrawing, DrawingController src/components/ Draw, DrawSurface, Toolbar, ToolIcon, Tooltip, MorphBar, … src/palette.ts SWATCHES, SWATCHES_COMPACT, MAX_SWATCHES, … apps/studio/ demo harness (Vite + React 19), uses `drawesome` as a workspace dep tests/ Playwright regression suite (Playwright 1.63, Portless) ``` -------------------------------- ### Implementing useDrawing in a React component Source: https://github.com/benjitaylor/drawesome/blob/master/_autodocs/api-reference/use-drawing.md Demonstrates how to initialize useDrawing and utilize its methods for committing strokes, managing gestures, and handling undo/redo/clear actions. ```tsx import { useDrawing } from 'drawesome' function Editor() { const drawing = useDrawing(savedStrokes) // discrete action: one history entry const addStroke = (s: Stroke) => drawing.commit([...drawing.strokes, s]) // gesture: begin/update/end — one history entry no matter how many updates const gesture = { start: () => drawing.begin(), move: (next: Stroke[]) => drawing.update(next), finish: () => drawing.end(), } // loading a document must not be undoable const loadFile = (strokes: Stroke[]) => drawing.reset(strokes) return ( <> ) } ``` -------------------------------- ### Download drawing as image Source: https://github.com/benjitaylor/drawesome/blob/master/README.md Use a ref to access the DrawHandle and call the download method to export the drawing as a PNG file. ```tsx const draw = useRef(null) await draw.current.download('sketch', 'png', 2) ``` -------------------------------- ### toPng(strokes, w, h, background, scale?) Source: https://github.com/benjitaylor/drawesome/blob/master/_autodocs/index.md Serializes strokes to a PNG Blob with given dimensions, background, and optional scale. ```APIDOC ## toPng(strokes, w, h, background, scale?) ### Description Serializes strokes to a PNG Blob. ### Signature `toPng(strokes: Stroke[], w: number, h: number, background: string, scale?: number) => Promise` ### Parameters - **strokes** (Stroke[]) - Required - The strokes to serialize. - **w** (number) - Required - Width of the PNG. - **h** (number) - Required - Height of the PNG. - **background** (string) - Required - Background color. - **scale** (number) - Optional - Scale factor. ### Returns - **Promise** - A promise resolving to a PNG Blob. ``` -------------------------------- ### FreehandOptions Source: https://github.com/benjitaylor/drawesome/blob/master/_autodocs/types.md The FreehandOptions type configures stroke rendering behavior, including size, thinning, smoothing, pressure simulation, and tapering. ```APIDOC ## FreehandOptions ### Description The FreehandOptions type defines configuration options for freehand stroke rendering, including size, thinning, smoothing, and pressure simulation. ### Type Definition ```tsx export type FreehandOptions = { size?: number; // width at rest — default 16 thinning?: number; // 0–1 speed/pressure narrowing — default 0.5 streamline?: number; // 0–1 smoothing — default 0.5 easing?: (t: number) => number; // pressure reshape — default identity simulatePressure?: boolean; // derive pressure from speed — default true openAt?: number; // opening width fraction — default 1 flatEnds?: boolean; // square ends — default false taperStart?: number; // fade-in distance px — default 0 taperEnd?: number; // fade-out distance px — default 0 nibAngle?: number; // degrees — default 0 nibContrast?: number; // 0–1 — default 0 variance?: number; // 0–1 per-stroke randomness — default 0 last?: boolean; // declared; not read by the implementation }; ``` ### Fields - **size** (number) - Optional - Width at rest, default 16. - **thinning** (number) - Optional - 0–1 speed/pressure narrowing, default 0.5. - **streamline** (number) - Optional - 0–1 smoothing, default 0.5. - **easing** (function) - Optional - Pressure reshape function, default identity. - **simulatePressure** (boolean) - Optional - Derive pressure from speed, default true. - **openAt** (number) - Optional - Opening width fraction, default 1. - **flatEnds** (boolean) - Optional - Square ends, default false. - **taperStart** (number) - Optional - Fade-in distance in pixels, default 0. - **taperEnd** (number) - Optional - Fade-out distance in pixels, default 0. - **nibAngle** (number) - Optional - Angle in degrees, default 0. - **nibContrast** (number) - Optional - 0–1 contrast, default 0. - **variance** (number) - Optional - 0–1 per-stroke randomness, default 0. - **last** (boolean) - Optional - Declared but not read by the implementation. ### Usage Accepted by: `getStroke`, produced by `Pen.options(size)`. ``` -------------------------------- ### Exporting and stroke management Source: https://github.com/benjitaylor/drawesome/blob/master/_autodocs/api-reference/draw.md Demonstrates how to handle export errors and retrieve strokes for persistence using the DrawHandle reference. ```tsx function Export({ draw }: { draw: React.RefObject }) { const save = async () => { try { await draw.current?.download('sketch', 'png', 2) } catch (err) { console.error('export failed:', err) // see errors.md — raw Error messages } } const snapshot: Stroke[] = draw.current?.getStrokes() ?? [] // persisting `snapshot` and passing it back as // is the documented round-trip. return } ``` -------------------------------- ### Ref Handle Methods Source: https://github.com/benjitaylor/drawesome/blob/master/README.md Methods available on the ref handle for programmatic control of the drawing surface. ```APIDOC ## Ref Handle Methods | Method | Type | Description | |--------|------|-------------| | `toSvg` | `() => string` | Exactly what's on screen, erasing and all | | `toPng` | `(scale?) => Promise` | `scale` multiplies the resolution | | `download` | `(name?, format?, scale?) => Promise` | Save straight to a file | | `getStrokes` | `() => Stroke[]` | | | `setStrokes` | `(strokes) => void` | Replaces the drawing, and its undo history | | `undo` / `redo` / `clear` | `() => void` | | | `getSize` | `() => Board` | The size the drawing is being made at | ``` -------------------------------- ### toPng Source: https://github.com/benjitaylor/drawesome/blob/master/_autodocs/api-reference/engine-serialize.md Rasterizes the drawing to a PNG blob. Returns a Promise. ```APIDOC ## toPng ### Description Rasterizes the drawing to a PNG blob. Returns a Promise. ### Signature ```tsx export async function toPng( strokes: Stroke[], width: number, height: number, background: string | null, scale = 2, ): Promise ``` ### Parameters - **strokes** (Stroke[]) - Required - Committed strokes in order. - **width** (number) - Required - Board width (logical). - **height** (number) - Required - Board height (logical). - **background** (string | null) - Required - CSS colour for the background; `null` or `"transparent"` emits no background. - **scale** (number) - Optional, default `2` - Device-pixel multiplier; the canvas is `Math.max(1, Math.round(width * scale))` × `Math.max(1, Math.round(height * scale))`. ### Returns A Promise that resolves to a PNG Blob. ### Errors - `new Error("Could not rasterise the drawing")` - image load error - `new Error("Could not get a 2D context")` - canvas context unavailable - `new Error("Could not encode the PNG")` - `toBlob` produced no blob ### Example ```tsx import { toPng } from 'drawesome' async function exportPng() { try { const blob = await toPng(strokes, 800, 600, 'transparent', 2) const url = URL.createObjectURL(blob) const a = document.createElement('a') a.href = url a.download = 'sketch.png' a.click() setTimeout(() => URL.revokeObjectURL(url), 0) } catch (err) { console.error('PNG export failed:', (err as Error).message) } } ``` ``` -------------------------------- ### FreehandOptions Source: https://github.com/benjitaylor/drawesome/blob/master/_autodocs/api-reference/engine-freehand.md The FreehandOptions type defines all configurable options for the getStroke function. It includes properties for stroke width, thinning, smoothing, easing, pressure simulation, tapering, nib behavior, and more. ```APIDOC ## FreehandOptions ### Description The FreehandOptions type configures the behavior of the getStroke function. Each option adjusts how the stroke is rendered, from width and smoothing to tapering and nib effects. ### Type Definition ```ts export type FreehandOptions = { /** Width of the stroke at rest. */ size?: number; /** 0–1: how much speed (or pressure) narrows the line. 0 is a fixed width. */ thinning?: number; /** 0–1: how much the input is smoothed before it's used. */ streamline?: number; /** Reshapes pressure before it becomes a width. */ easing?: (t: number) => number; /** Derive pressure from speed, for input that reports none. */ simulatePressure?: boolean; /** How wide the stroke opens, as a fraction of full pressure. Default 1. */ openAt?: number; /** Square the ends off instead of rounding them. Default false. */ flatEnds?: boolean; /** Distance over which the line fades in at the start, in px. */ taperStart?: number; /** Distance over which the line fades out at the end, in px. */ taperEnd?: number; /** Angle of the nib, in degrees. */ nibAngle?: number; /** 0–1: how much narrower travel along the nib gets. 0 is a round nib. */ nibContrast?: number; /** 0–1: how much this stroke may differ from a perfectly regular one. */ variance?: number; /** Whether the stroke is finished. */ last?: boolean; }; ``` ### Option Defaults | Option | Type | Default | Description | |--------|------|---------|-------------| | `size` | `number` | `16` | Resting width in px. | | `thinning` | `number` | `0.5` | 0–1 fraction by which speed (or pressure) narrows the line; `0` = fixed width. | | `streamline` | `number` | `0.5` | 0–1 input smoothing. | | `easing` | `(t: number) => number` | `(t) => t` | Reshapes pressure before it becomes a width. | | `simulatePressure` | `boolean` | `true` | Derive pressure from speed when the input reports none. | | `taperStart` | `number` | `0` | Fade-in distance, px. | | `taperEnd` | `number` | `0` | Fade-out distance, px. | | `variance` | `number` | `0` | Per-stroke randomness, 0–1. | | `nibAngle` | `number` | `0` | Nib angle, degrees. | | `nibContrast` | `number` | `0` | How much narrower travel *along* the nib gets. | | `openAt` | `number` | `1` | How wide the stroke opens, as a fraction of full pressure. | | `flatEnds` | `boolean` | `false` | Square ends instead of rounded discs. | | `last` | `boolean` | — | Declared in the type and passed by `strokePath` (`last: isComplete`), but **not read anywhere in the current implementation** (verified against source — it is not in the destructuring and no later reference exists). Tapering is applied unconditionally; treat this field as reserved. | ``` -------------------------------- ### Tools Props Source: https://github.com/benjitaylor/drawesome/blob/master/README.md Props that control the available tools, ink behavior, palette, and appearance. ```APIDOC ## Tools Props | Prop | Type | Default | Description | |------|------|---------|-------------| | `tools` | `PenId[]` | all seven | Which pens appear, and in what order | | `eraser` | `boolean` | `true` | Whether the eraser is offered | | `ink` | `"auto" \| "shared" \| "per-tool"` | `"auto"` | Whether a colour applies to every tool or only the one in hand | | `swatches` | `string[]` | 18 built-in | Your own palette, clamped to what the bar holds | | `look` | `"classic" \| "studio"` | `"classic"` | Tools shaded flat, or lit as objects | | `gauge` | `boolean` | `false` | Print the current size on the barrel | ``` -------------------------------- ### useDrawing(initial?: Stroke[]): DrawingController Source: https://github.com/benjitaylor/drawesome/blob/master/_autodocs/api-reference/use-drawing.md Initializes the drawing state with an optional initial stroke list and returns a controller object for managing strokes, history, and gestures. ```APIDOC ## useDrawing(initial?: Stroke[]): DrawingController ### Description Initializes the drawing state with an optional initial stroke list and returns a controller object for managing strokes, history, and gestures. ### Signature ```tsx export function useDrawing(initial: Stroke[] = []): DrawingController ``` ### Parameters - **initial** (Stroke[]) - Optional - The stroke list to start from (initial useState value). Defaults to []. ``` -------------------------------- ### getStroke(points, options) Source: https://github.com/benjitaylor/drawesome/blob/master/_autodocs/api-reference/engine-freehand.md Computes stroke outline rings from an array of points and an options object. Returns an array of rings that can be used to render a stroke path. ```APIDOC ## getStroke(points, options) ### Description Computes stroke outline rings from an array of points and an options object. Returns an array of rings that can be used to render a stroke path. ### Method Function call ### Endpoint N/A (SDK function) ### Parameters #### points (Array) - Required - An array of points, each represented as a tuple [x, y, pressure]. Example: [[10, 10, 0.5], [20, 14, 0.6], [30, 22, 0.8], [40, 40, 1]] #### options (Object) - Optional - **size** (number) - Optional - The stroke size. - **thinning** (number) - Optional - The thinning factor. - **streamline** (number) - Optional - The streamline factor. - **simulatePressure** (boolean) - Optional - Whether to simulate pressure. - **taperStart** (number) - Optional - Taper at the start of the stroke. - **taperEnd** (number) - Optional - Taper at the end of the stroke. ### Request Example ```tsx import { getStroke } from 'drawesome' const points: Point[] = [[10, 10, 0.5], [20, 14, 0.6], [30, 22, 0.8], [40, 40, 1]] const rings = getStroke(points, { size: 8, thinning: 0.5, streamline: 0.5, simulatePressure: true, taperStart: 0, taperEnd: 24, }) ``` ### Response #### Success Response Returns an array of rings (each ring is an array of points) that can be rendered as a path. For example, you can use a helper like ringsToPath to convert rings to a path string. #### Response Example ```tsx // rings is an array of rings, e.g., [[[x1, y1], [x2, y2], ...], ...] // ``` ### Error Handling - Zero or negative size and empty input return an empty array ([]). - Malformed points (non-tuples) are not validated and would surface as NaN coordinates. ``` -------------------------------- ### Configure Draw tools and controls Source: https://github.com/benjitaylor/drawesome/blob/master/README.md Customize the available drawing tools and disable specific controls using the tools and controls props. ```tsx ``` -------------------------------- ### Standalone DrawSurface usage Source: https://github.com/benjitaylor/drawesome/blob/master/_autodocs/api-reference/drawsurface.md Demonstrates using DrawSurface with custom state management via useDrawing. This configuration is equivalent to setting chrome={false}. ```tsx import { useDrawing, DrawSurface, Toolbar } from 'drawesome' function Canvas() { const drawing = useDrawing([]) return ( <> {/* layout your own chrome, or use — see toolbar.md */} ) } ``` -------------------------------- ### DrawHandle Source: https://github.com/benjitaylor/drawesome/blob/master/_autodocs/api-reference/draw.md The DrawHandle ref handle exposes methods for exporting, downloading, manipulating strokes, and controlling history. Each method is documented with its signature and behavior. ```APIDOC ## DrawHandle ### Description The DrawHandle ref handle provides methods to export the drawing, download it, get and set strokes, and perform history operations. ### Methods #### toSvg() - **Returns**: `string` - Exactly what's on screen, erasing and all (masks included), as a standalone SVG document. #### toPng(scale?) - **Parameters**: - `scale` (number) - Optional - Multiplies the resolution (default `2`, i.e. 2× device pixels). - **Returns**: `Promise` - Rejects on rasterization failure. #### download(name?, format?, scale?) - **Parameters**: - `name` (string) - Optional - Defaults to `"drawing"`. - `format` ("svg" | "png") - Optional - Defaults to `"svg"`. - `scale` (number) - Optional - Defaults to `2`. - **Returns**: `Promise` - Saves to a file. Filename is `${name}.${format}`; PNG goes through `toPng`, SVG through `toSvg` wrapped in a Blob. Revokes the object URL on the next turn. #### getStrokes() - **Returns**: `Stroke[]` - Current committed strokes. #### setStrokes(next) - **Parameters**: - `next` (Stroke[]) - Required - Replaces the drawing and pushes one history entry (via `drawing.commit`). - **Returns**: `void` #### undo() - **Returns**: `void` - History operation on the internal controller. #### redo() - **Returns**: `void` - History operation on the internal controller. #### clear() - **Returns**: `void` - History operation on the internal controller. #### getSize() - **Returns**: `Board` - The surface size the drawing is being made at (`board ?? measured`). ``` -------------------------------- ### getStroke(raw, options) Source: https://github.com/benjitaylor/drawesome/blob/master/_autodocs/api-reference/engine-freehand.md Computes the swept outline of a freehand stroke from sampled input points. Returns an array of rings, each ring an array of [x, y] points, representing closed polygons that cover the stroke's outline. ```APIDOC ## getStroke(raw, options) ### Description Computes the swept outline of a freehand stroke from sampled input points. Returns an array of rings, each ring an array of [x, y] points, representing closed polygons that cover the stroke's outline. ### Signature ```tsx export function getStroke( raw: Point[], options: FreehandOptions = {}, ): Vec[][] ``` ### Parameters - **raw** (Point[]) - Required - Sampled input points [x, y, pressure], pressure 0-1 (or -1 to mean "no pressure" - negative pressure is replaced by 0.5 in walk). - **options** (FreehandOptions) - Optional - Shaping options. Defaults to {}. ### Return Contract - Returns [] when size <= 0 or raw.length === 0. - A single input point (a tap) yields exactly one disc ring - a dot, sized by the stroke's opening width (openAt, tapered start, or the MIN_RADIUS floor of 0.4). - Any other input yields the swept outline: shaft bands between consecutive points plus joint discs (skipped for flat-ended caps), ending with a disc at the last point unless flatEnds. ### Algorithm Outline 1. **walk** - Exponential smoothing (t = 0.15 + (1 - streamline) * 0.85), speed measured on the input (not the resampled spacing, so it reflects the hand), fixed-spacing resampling (step = max(0.6, min(3, nib / 3))), always finishing exactly on the last input point. 2. **Per-stroke variance** - Seeded from raw[0] only (module noise() - a deterministic PRNG), so the outline is stable across pointer moves: load scale (±10% × variance), asymmetric tapers, varying bite (thinning response), and a 3-wave amplitude pulse along the stroke (depth = 0.115 * variance). 3. **Width per point** - Simulated pressure chases speed (FAST = 26 px/samples, exponential chase over RESPONSE_DISTANCE = 14 px) or uses hardware pressure; nib-contrast modulation from the angle of travel vs nibAngle (r *= 1 - nibContrast * (1 - |sin a|)); then a two-pass moving-average blur of the radius profile (window max(1, round(nib / step))). 4. **Tapers** - inLen = min(fadeIn, total * 0.5) / outLen = min(fadeOut, total * 0.5), radius *= TAPER_TIP + (1 - TAPER_TIP) * pow(t, 0.55) with TAPER_TIP = 0.1; radii floored at MIN_RADIUS = 0.4. 5. **Geometry** - Overlap-extended bands (OVERLAP = 0.35 of a step past each end), all rings wound the same way (nonzero fill); joint discs only where actually needed (cap at the start unless flat, max(r0, r1) * bend > 0.12 for turns, or width steps > 0.4), and discs are circumscribed (rr = r / cos(π/steps)) so polygons' edges sit on the true radius. ``` -------------------------------- ### Define PENS and PEN_BY_ID constants Source: https://github.com/benjitaylor/drawesome/blob/master/_autodocs/api-reference/engine-pens.md Exports the array of pen definitions and a lookup map for accessing pens by their ID. ```tsx export const PENS: Pen[] = [ /* seven entries, see below */ ]; export const PEN_BY_ID = Object.fromEntries( PENS.map((p) => [p.id, p]), ) as Record; ``` -------------------------------- ### Draw Component Usage Source: https://github.com/benjitaylor/drawesome/blob/master/_autodocs/api-reference/draw.md Basic usage of the Draw component with tools and controls props, and a ref to access the DrawHandle. ```APIDOC ## Draw Component ### Description Renders a drawing surface with configurable tools and controls. The component accepts a ref to access the DrawHandle for imperative operations. ### Usage Example ```tsx import { useRef } from 'react' import { Draw, type DrawHandle } from 'drawesome' import 'drawesome/styles.css' function Canvas() { const draw = useRef(null) return (
) } ``` ### Props - **ref** (RefObject) - Required - Reference to the DrawHandle for imperative methods. - **tools** (string[]) - Optional - List of tool names to enable. Example: ['pencil', 'marker', 'highlighter']. - **controls** (object) - Optional - Configuration for UI controls. Example: { undo: false, clear: false }. - **initialStrokes** (Stroke[]) - Optional - Initial strokes to render, used for round-tripping. ### Keyboard Shortcuts - **⌘Z / Ctrl+Z** - Undo - **⇧⌘Z / Ctrl+Shift+Z, ⌘Y / Ctrl+Y** - Redo - **E** - Eraser (only while eraser is on) - **[ / ]** - Nudge size down/up (pen clamps 1-80, eraser clamps 1-120) - **c, p, f, m, h, b, g** - Select pencil/pen/fineliner/marker/highlighter/brush/fountain (each pen's key field) ### Notes - Keyboard shortcuts are bound to window keydown and are scoped to the drawing root. - Holding Shift while drawing locks the stroke to the nearest of eight directions. ``` -------------------------------- ### getSvgPathFromStroke and streamline signatures Source: https://github.com/benjitaylor/drawesome/blob/master/_autodocs/api-reference/engine-geometry.md Function signatures for the internal path builder and smoothing utility. getSvgPathFromStroke joins rings into M/L/Z paths with coordinates rounded to one decimal, skipping rings with fewer than three points. streamline returns input unchanged when points.length < 3 or amount <= 0. ```tsx export function getSvgPathFromStroke(rings: number[][][]): string export function streamline(points: Point[], amount: number): Point[] ``` -------------------------------- ### InkMode, MotionPreset, MotionOptions Source: https://github.com/benjitaylor/drawesome/blob/master/_autodocs/types.md These types define ink behavior and motion presets for the Draw component. ```APIDOC ## InkMode, MotionPreset, MotionOptions ### Description These types define ink behavior and motion presets for the Draw component. ### Types #### InkMode - **Values**: `"shared" | "per-tool" | "auto"` - **Description**: Determines how ink settings are applied across tools. #### MotionPreset - **Values**: `"rise" | "none"` - **Description**: Preset animation styles for motion. #### MotionOptions - **Properties**: - **in** (MotionPreset) - Optional - The entrance motion preset. - **out** (MotionPreset) - Optional - The exit motion preset. - **duration** (number) - Optional - The duration of the motion in seconds. - **Description**: Configuration options for motion animations. ``` -------------------------------- ### strokePath(pen, size, points, isComplete?, shape?) Source: https://github.com/benjitaylor/drawesome/blob/master/_autodocs/index.md Generates an SVG path 'd' string for a stroke based on pen, size, points, and optional completion and shape parameters. ```APIDOC ## strokePath(pen, size, points, isComplete?, shape?) ### Description Generates an SVG path 'd' string for a stroke. ### Signature `strokePath(pen: Pen, size: number, points: Point[], isComplete?: boolean, shape?: StrokeShape) => string` ### Parameters - **pen** (Pen) - Required - The pen used for the stroke. - **size** (number) - Required - The stroke size. - **points** (Point[]) - Required - The points of the stroke. - **isComplete** (boolean) - Optional - Whether the stroke is complete. - **shape** (StrokeShape) - Optional - The shape of the stroke. ### Returns - **string** - SVG path 'd' string. ``` -------------------------------- ### Surface Props Source: https://github.com/benjitaylor/drawesome/blob/master/README.md Props that control the drawing surface: board size, background, initial strokes, and change callback. ```APIDOC ## Surface Props | Prop | Type | Default | Description | |------|------|---------|-------------| | `board` | `{ w, h }` | element size | Fixed drawing area. Omit and it matches the element | | `background` | `string` | `"#ffffff"` | Any CSS colour, `"transparent"` to paint nothing, or `"checker"` | | `initialStrokes` | `Stroke[]` | `[]` | Strokes to open with | | `onChange` | `(strokes) => void` | | Fires on every finished stroke and every erase | | `className` | `string` | | Passed to the root element, along with `style` | | `style` | `CSSProperties` | | | ``` -------------------------------- ### DrawHandle Methods Source: https://github.com/benjitaylor/drawesome/blob/master/_autodocs/api-reference/draw.md Methods available on the DrawHandle ref for exporting and retrieving strokes. ```APIDOC ## DrawHandle Methods ### Description Methods exposed via the DrawHandle ref for exporting the drawing and retrieving stroke data. ### Methods #### download(filename, format, scale) - **filename** (string) - Required - Base name for the downloaded file. - **format** (string) - Required - Export format, e.g., 'png'. - **scale** (number) - Required - Scale factor for the export. - **Returns**: Promise - Resolves when download completes. - **Throws**: Error - On export failure (see errors.md for raw Error messages). #### getStrokes() - **Returns**: Stroke[] - Array of stroke objects representing the current drawing. ### Usage Example ```tsx function Export({ draw }: { draw: React.RefObject }) { const save = async () => { try { await draw.current?.download('sketch', 'png', 2) } catch (err) { console.error('export failed:', err) } } const snapshot: Stroke[] = draw.current?.getStrokes() ?? [] // persisting snapshot and passing it back as // is the documented round-trip. return } ``` ``` -------------------------------- ### polylinePath(points: Point[]): string Source: https://github.com/benjitaylor/drawesome/blob/master/_autodocs/api-reference/engine-geometry.md Generates a smoothed quadratic-curved path string from raw input points. Returns an empty string for empty input, or a small stub path for a single point to keep it visible as a dot. ```APIDOC ## polylinePath(points: Point[]): string ### Description Generates a smoothed quadratic-curved path string from raw input points. Returns an empty string for empty input, or a small stub path for a single point to keep it visible as a dot. ### Signature ```tsx export function polylinePath(points: Point[]): string ``` ### Parameters - **points** (Point[]) - Required - Raw input points. ### Returns - **string** - A quadratic-curved path: `M x0 y0 Q x1 y1 mid... L xn yn` (midpoints as curve ends). Empty input returns `""`; a single point returns a 0.01-length stub path (`M x y l0.01 0.01`). Numbers rounded to 2 decimals. ### Usage Notes Used for the eraser's swept path in masks and in `toSvg` exports. ``` -------------------------------- ### ToolIcon component Source: https://github.com/benjitaylor/drawesome/blob/master/_autodocs/index.md React memo component that renders the drawn implements, usable standalone or as the minimized disc icon. ```APIDOC ## ToolIcon ### Description React memo component that renders the drawn implements. ### Props - None documented explicitly. ``` -------------------------------- ### useDrawing(initial?) Source: https://github.com/benjitaylor/drawesome/blob/master/_autodocs/index.md React hook that returns a DrawingController for managing strokes with transaction API and undo/redo/clear/reset. ```APIDOC ## useDrawing(initial?) ### Description React hook that provides a DrawingController for managing strokes. ### Signature `useDrawing(initial?: Stroke[]) => DrawingController` ### Parameters - **initial** (Stroke[]) - Optional - Initial strokes. ### Returns - **DrawingController** - Controller with stroke list and transaction API (commit/begin/update/end) plus undo/redo/clear/reset. ``` -------------------------------- ### polylinePath(points) Source: https://github.com/benjitaylor/drawesome/blob/master/_autodocs/index.md Generates a smoothed polyline SVG path 'd' string from the given points. ```APIDOC ## polylinePath(points) ### Description Generates a smoothed polyline SVG path 'd' string. ### Signature `polylinePath(points: Point[]) => string` ### Parameters - **points** (Point[]) - Required - The points to create the polyline. ### Returns - **string** - SVG path 'd' string. ```