# Using with AI assistants (/react-sketch-canvas/agentic-tools) If you are pairing with an AI assistant, giving it the docs up front saves a lot of guesswork about props, refs, and export APIs. This site publishes documentation in the `llms.txt` format so tools can fetch it directly. ## What is `llms.txt`? [#what-is-llmstxt] `llms.txt` is a small convention for making documentation easy for LLMs to consume. A site exposes two files at well-known paths: * [`/llms.txt`](/react-sketch-canvas/llms.txt): a short, structured index of every docs page with links. * [`/llms-full.txt`](/react-sketch-canvas/llms-full.txt): the full text of the docs concatenated into one file, ready to drop into a context window. Most assistants will follow the links in `llms.txt` themselves; for tools without web access, paste `llms-full.txt` once and the assistant has the whole reference. Learn more at [llmstxt.org](https://llmstxt.org/), the community-curated directory at [github.com/AnswerDotAI/llms-txt](https://github.com/AnswerDotAI/llms-txt), and the [llms.txt getting-started guide on llmstxthub](https://llmstxthub.com/guides/getting-started-llms-txt). ## Project note [#project-note] Version 8 of React Sketch Canvas was built with help from AI coding assistants, including Claude Code and Codex. I reviewed, tested, and shipped the changes, but the workflow leaned heavily on model-generated implementation work. If you are curious about that style of development, Simon Willison's [Agentic Engineering Patterns](https://simonwillison.net/guides/agentic-engineering-patterns/) is a useful overview. # react-sketch-canvas (/react-sketch-canvas/api) ## Interfaces [#interfaces] * [CanvasPath](/react-sketch-canvas/api/interfaces/canvaspath/) * [CanvasProps](/react-sketch-canvas/api/interfaces/canvasprops/) * [CanvasRef](/react-sketch-canvas/api/interfaces/canvasref/) * [ExportImageOptions](/react-sketch-canvas/api/interfaces/exportimageoptions/) * [Point](/react-sketch-canvas/api/interfaces/point/) * [ReactSketchCanvasProps](/react-sketch-canvas/api/interfaces/reactsketchcanvasprops/) * [ReactSketchCanvasRef](/react-sketch-canvas/api/interfaces/reactsketchcanvasref/) ## Type Aliases [#type-aliases] * [AllowOnlyPointerType](/react-sketch-canvas/api/type-aliases/allowonlypointertype/) * [EraserMode](/react-sketch-canvas/api/type-aliases/erasermode/) * [ExportImageType](/react-sketch-canvas/api/type-aliases/exportimagetype/) ## Variables [#variables] * [Canvas](/react-sketch-canvas/api/variables/canvas/) * [ReactSketchCanvas](/react-sketch-canvas/api/variables/reactsketchcanvas/) # CanvasPath (/react-sketch-canvas/api/interfaces/canvaspath) Defined in: [types/canvas.ts:74](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/types/canvas.ts#L74) A single stroke recorded by the sketch canvas. ## Remarks [#remarks] `CanvasPath` is the persistence format returned by [ReactSketchCanvasRef.exportPaths](/react-sketch-canvas/api/interfaces/reactsketchcanvasref/#exportpaths) and accepted by [ReactSketchCanvasRef.loadPaths](/react-sketch-canvas/api/interfaces/reactsketchcanvasref/#loadpaths). Store this object if you want to save a drawing and replay it later. `drawMode` decides whether the stroke paints (`true`) or erases (`false`). Eraser strokes are stored as paths so exports and undo/redo can preserve the same visual result. ## Properties [#properties] ### drawMode [#drawmode] > `readonly` **drawMode**: `boolean` Defined in: [types/canvas.ts:98](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/types/canvas.ts#L98) Whether the stroke draws color (`true`) or erases existing strokes (`false`). *** ### endTimestamp? [#endtimestamp] > `readonly` `optional` **endTimestamp?**: `number` Defined in: [types/canvas.ts:114](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/types/canvas.ts#L114) Timestamp captured when the stroke ends, in milliseconds since the Unix epoch. #### Remarks [#remarks-1] This is only present when `withTimestamp` is enabled. *** ### paths [#paths] > `readonly` **paths**: [`Point`](/react-sketch-canvas/api/interfaces/point/)\[] Defined in: [types/canvas.ts:81](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/types/canvas.ts#L81) Ordered points that make up this stroke. #### Remarks [#remarks-2] A stroke can contain a single point, which is rendered as a dot. *** ### startTimestamp? [#starttimestamp] > `readonly` `optional` **startTimestamp?**: `number` Defined in: [types/canvas.ts:106](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/types/canvas.ts#L106) Timestamp captured when the stroke starts, in milliseconds since the Unix epoch. #### Remarks [#remarks-3] This is only present when `withTimestamp` is enabled. *** ### strokeColor [#strokecolor] > `readonly` **strokeColor**: `string` Defined in: [types/canvas.ts:93](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/types/canvas.ts#L93) Stroke color used when `drawMode` is `true`. #### Remarks [#remarks-4] Eraser paths are stored with an internal mask color, but consumers usually only need to preserve the value returned by `exportPaths`. *** ### strokeWidth [#strokewidth] > `readonly` **strokeWidth**: `number` Defined in: [types/canvas.ts:85](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/types/canvas.ts#L85) Stroke width in pixels. # CanvasProps (/react-sketch-canvas/api/interfaces/canvasprops) Defined in: [Canvas/types.ts:31](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L31) Props for the low-level [Canvas](/react-sketch-canvas/api/variables/canvas/) component. ## Remarks [#remarks] These props are primarily useful for composing a custom state manager around the low-level SVG canvas. Application code normally uses [ReactSketchCanvasProps](/react-sketch-canvas/api/interfaces/reactsketchcanvasprops/). ## Properties [#properties] ### allowOnlyPointerType [#allowonlypointertype] > **allowOnlyPointerType**: [`AllowOnlyPointerType`](/react-sketch-canvas/api/type-aliases/allowonlypointertype/) Defined in: [Canvas/types.ts:84](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L84) Pointer device class allowed to draw on the canvas. #### Remarks [#remarks-1] Other pointer devices can still interact with the page, but their drawing events are ignored by the canvas. #### Default Value [#default-value] `"all"` *** ### backgroundImage [#backgroundimage] > **backgroundImage**: `string` Defined in: [Canvas/types.ts:100](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L100) Background image shown behind all strokes. #### Remarks [#remarks-2] Accepts any SVG `` `href` value, including a URL or data URI. When exporting with the background image enabled, remote images must allow cross-origin access. The value is treated as trusted: it is loaded directly into an SVG `` element and, for SVG data URIs, parsed with `DOMParser` to read its viewBox. Do not pass attacker-controlled strings here without validating them first. #### Default Value [#default-value-1] `""` *** ### canvasColor [#canvascolor] > **canvasColor**: `string` Defined in: [Canvas/types.ts:113](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L113) Background color shown when no background image is configured. #### Remarks [#remarks-3] `canvasColor` is also painted underneath every JPEG export, even when a background image is included, because JPEG cannot represent transparent pixels. With `preserveBackgroundImageAspectRatio="meet"` (or any value that letterboxes the image), the letterbox regions of a JPEG export will be filled with `canvasColor`. #### Default Value [#default-value-2] `"white"` *** ### className? [#classname] > `optional` **className?**: `string` Defined in: [Canvas/types.ts:119](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L119) CSS class name applied to the outer canvas wrapper. #### Default Value [#default-value-3] `"react-sketch-canvas"` *** ### exportWithBackgroundImage [#exportwithbackgroundimage] > **exportWithBackgroundImage**: `boolean` Defined in: [Canvas/types.ts:129](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L129) Whether exported images and SVGs include `backgroundImage`. #### Remarks [#remarks-4] Set this to `false` when the background image is only a drawing guide and should not be part of exported output. #### Default Value [#default-value-4] ```ts false ``` *** ### height [#height] > **height**: `string` Defined in: [Canvas/types.ts:139](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L139) CSS height of the canvas wrapper. #### Remarks [#remarks-5] Accepts any valid CSS height value, such as `"400px"`, `"60vh"`, or `"100%"`. #### Default Value [#default-value-5] `"100%"` *** ### id? [#id] > `optional` **id?**: `string` Defined in: [Canvas/types.ts:151](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L151) DOM id applied to the rendered SVG canvas. #### Remarks [#remarks-6] Internal SVG definitions such as masks and background patterns are isolated per canvas instance, so multiple canvases can use the default id without sharing those internal references. Provide a unique id when application code needs to select or label a specific canvas element. #### Default Value [#default-value-6] `"react-sketch-canvas"` *** ### isDrawing [#isdrawing] > **isDrawing**: `boolean` Defined in: [Canvas/types.ts:45](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L45) Whether a pointer stroke is currently active. #### Remarks [#remarks-7] While this is `true`, pointer movement is forwarded to `onPointerMove`. *** ### onPointerDown [#onpointerdown] > **onPointerDown**: (`point`, `isEraser?`) => `void` Defined in: [Canvas/types.ts:57](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L57) Called when the user starts a stroke. #### Parameters [#parameters] ##### point [#point] [`Point`](/react-sketch-canvas/api/interfaces/point/) Canvas-relative point where the stroke starts. ##### isEraser? [#iseraser] `boolean` Whether the pointer should create an eraser stroke. #### Returns [#returns] `void` Nothing. #### Remarks [#remarks-8] The callback receives the pointer coordinate normalized to the canvas and an eraser flag when a pen eraser button is detected. *** ### onPointerMove [#onpointermove] > **onPointerMove**: (`point`) => `void` Defined in: [Canvas/types.ts:64](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L64) Called when the active pointer moves while drawing. #### Parameters [#parameters-1] ##### point [#point-1] [`Point`](/react-sketch-canvas/api/interfaces/point/) Canvas-relative point for the current pointer position. #### Returns [#returns-1] `void` Nothing. *** ### onPointerUp [#onpointerup] > **onPointerUp**: () => `void` Defined in: [Canvas/types.ts:74](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L74) Called when the active stroke ends. #### Returns [#returns-2] `void` Nothing. #### Remarks [#remarks-9] `Canvas` listens for `pointerup` on the document so a stroke can finish even when the pointer is released outside the canvas element. *** ### paths [#paths] > **paths**: [`CanvasPath`](/react-sketch-canvas/api/interfaces/canvaspath/)\[] Defined in: [Canvas/types.ts:38](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L38) Paths rendered on the SVG canvas. #### Remarks [#remarks-10] `Canvas` is controlled. Pass the complete path list for each render. *** ### preserveBackgroundImageAspectRatio? [#preservebackgroundimageaspectratio] > `optional` **preserveBackgroundImageAspectRatio?**: `string` Defined in: [Canvas/types.ts:161](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L161) SVG `preserveAspectRatio` value used for `backgroundImage`. #### Remarks [#remarks-11] See the MDN reference for accepted values: [https://developer.mozilla.org/docs/Web/SVG/Attribute/preserveAspectRatio](https://developer.mozilla.org/docs/Web/SVG/Attribute/preserveAspectRatio). #### Default Value [#default-value-7] `"none"` *** ### readOnly? [#readonly] > `optional` **readOnly?**: `boolean` Defined in: [Canvas/types.ts:209](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L209) Whether pointer drawing is disabled. #### Remarks [#remarks-12] Existing paths are still rendered and ref export methods still work. #### Default Value [#default-value-8] ```ts false ``` *** ### style [#style] > **style**: `CSSProperties` Defined in: [Canvas/types.ts:173](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L173) Inline styles applied to the outer canvas wrapper. #### Remarks [#remarks-13] The component sets `userSelect: "none"` to avoid browser selection highlights while drawing. It sets `touchAction: "none"` for touch drawing, and `touchAction: "pan-x pan-y pinch-zoom"` in pen-only mode so touch can still scroll parent containers. #### Default Value [#default-value-9] ```ts The package default canvas border style. ``` *** ### svgStyle [#svgstyle] > **svgStyle**: `CSSProperties` Defined in: [Canvas/types.ts:179](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L179) Inline styles applied to the internal SVG element. #### Default Value [#default-value-10] `{}` *** ### touchAction? [#touchaction] > `optional` **touchAction?**: `TouchAction` Defined in: [Canvas/types.ts:223](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L223) CSS `touch-action` applied to the canvas wrapper. #### Remarks [#remarks-14] The default is `"none"` when the canvas accepts touch drawing, so single finger gestures draw rather than scroll. Override this when you need the surrounding page to remain scrollable; for example, set `"pan-y"` to let users scroll vertically while still drawing with one finger. The browser will start a native pan only when the gesture matches the configured axis, so single-finger drawing continues to work. #### Default Value [#default-value-11] `"none"` for touch-drawing modes; `"pan-x pan-y pinch-zoom"` for pen / mouse only modes. *** ### width [#width] > **width**: `string` Defined in: [Canvas/types.ts:200](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L200) CSS width of the canvas wrapper. #### Remarks [#remarks-15] Accepts any valid CSS width value, such as `"600px"`, `"100%"`, or `"80vw"`. #### Default Value [#default-value-12] `"100%"` *** ### withViewBox? [#withviewbox] > `optional` **withViewBox?**: `boolean` Defined in: [Canvas/types.ts:190](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L190) Whether the internal SVG should include a viewBox based on the latest measured canvas size. #### Remarks [#remarks-16] Enable this when you need SVG output that scales predictably with the rendered canvas dimensions. #### Default Value [#default-value-13] ```ts false ``` # CanvasRef (/react-sketch-canvas/api/interfaces/canvasref) Defined in: [Canvas/types.ts:231](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L231) Imperative ref API exposed by the low-level [Canvas](/react-sketch-canvas/api/variables/canvas/) component. ## Extended by [#extended-by] * [`ReactSketchCanvasRef`](/react-sketch-canvas/api/interfaces/reactsketchcanvasref/) ## Properties [#properties] ### exportImage [#exportimage] > **exportImage**: (`imageType`, `options?`) => `Promise`\<`string`> Defined in: [Canvas/types.ts:243](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L243) Export the current canvas as a raster image data URL. #### Parameters [#parameters] ##### imageType [#imagetype] [`ExportImageType`](/react-sketch-canvas/api/type-aliases/exportimagetype/) Image format to create. ##### options? [#options] [`ExportImageOptions`](/react-sketch-canvas/api/interfaces/exportimageoptions/) Optional export dimensions. #### Returns [#returns] `Promise`\<`string`> Promise that resolves to a `data:image/*` URL. #### Remarks [#remarks] The output includes the currently rendered strokes. Background image export depends on the `exportWithBackgroundImage` prop. *** ### exportSvg [#exportsvg] > **exportSvg**: () => `Promise`\<`string`> Defined in: [Canvas/types.ts:256](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L256) Export the current canvas as SVG markup. #### Returns [#returns-1] `Promise`\<`string`> Promise that resolves to SVG markup. #### Remarks [#remarks-1] The returned string contains the cloned SVG element after export-specific background handling has been applied. # ExportImageOptions (/react-sketch-canvas/api/interfaces/exportimageoptions) Defined in: [types/canvas.ts:23](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/types/canvas.ts#L23) Size options for raster image exports. ## Remarks [#remarks] When omitted, the exported image uses the rendered canvas element's current width and height. Provide both values to export a fixed-size image regardless of the on-screen canvas size. ## Properties [#properties] ### height? [#height] > `readonly` `optional` **height?**: `number` Defined in: [types/canvas.ts:35](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/types/canvas.ts#L35) Height of the exported image in pixels. #### Default Value [#default-value] ```ts The current rendered canvas height. ``` *** ### width? [#width] > `readonly` `optional` **width?**: `number` Defined in: [types/canvas.ts:29](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/types/canvas.ts#L29) Width of the exported image in pixels. #### Default Value [#default-value-1] ```ts The current rendered canvas width. ``` # Point (/react-sketch-canvas/api/interfaces/point) Defined in: [types/canvas.ts:48](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/types/canvas.ts#L48) A two-dimensional coordinate on the canvas. ## Remarks [#remarks] Coordinates are measured in CSS pixels from the top-left corner of the rendered canvas. Pointer events, exported paths, and loaded paths all use this coordinate system. ## Properties [#properties] ### x [#x] > `readonly` **x**: `number` Defined in: [types/canvas.ts:52](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/types/canvas.ts#L52) Horizontal coordinate in pixels from the left edge of the canvas. *** ### y [#y] > `readonly` **y**: `number` Defined in: [types/canvas.ts:56](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/types/canvas.ts#L56) Vertical coordinate in pixels from the top edge of the canvas. # ReactSketchCanvasProps (/react-sketch-canvas/api/interfaces/reactsketchcanvasprops) Defined in: [ReactSketchCanvas/types.ts:27](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/ReactSketchCanvas/types.ts#L27) Props for the stateful [ReactSketchCanvas](/react-sketch-canvas/api/variables/reactsketchcanvas/) component. ## Remarks [#remarks] `ReactSketchCanvas` composes the low-level [CanvasProps](/react-sketch-canvas/api/interfaces/canvasprops/) with drawing state management. You can pass sizing, styling, background, pointer, and export props from `CanvasProps`; path state and pointer callbacks are managed internally by the component. ## Extends [#extends] * `Partial`\<`Omit`\<[`CanvasProps`](/react-sketch-canvas/api/interfaces/canvasprops/), `"paths"` | `"isDrawing"` | `"onPointerDown"` | `"onPointerMove"` | `"onPointerUp"`>> ## Properties [#properties] ### allowOnlyPointerType? [#allowonlypointertype] > `optional` **allowOnlyPointerType?**: [`AllowOnlyPointerType`](/react-sketch-canvas/api/type-aliases/allowonlypointertype/) Defined in: [Canvas/types.ts:84](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L84) Pointer device class allowed to draw on the canvas. #### Remarks [#remarks-1] Other pointer devices can still interact with the page, but their drawing events are ignored by the canvas. #### Default Value [#default-value] `"all"` #### Inherited from [#inherited-from] [`CanvasProps`](/react-sketch-canvas/api/interfaces/canvasprops/).[`allowOnlyPointerType`](/react-sketch-canvas/api/interfaces/canvasprops/#allowonlypointertype) *** ### backgroundImage? [#backgroundimage] > `optional` **backgroundImage?**: `string` Defined in: [Canvas/types.ts:100](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L100) Background image shown behind all strokes. #### Remarks [#remarks-2] Accepts any SVG `` `href` value, including a URL or data URI. When exporting with the background image enabled, remote images must allow cross-origin access. The value is treated as trusted: it is loaded directly into an SVG `` element and, for SVG data URIs, parsed with `DOMParser` to read its viewBox. Do not pass attacker-controlled strings here without validating them first. #### Default Value [#default-value-1] `""` #### Inherited from [#inherited-from-1] [`CanvasProps`](/react-sketch-canvas/api/interfaces/canvasprops/).[`backgroundImage`](/react-sketch-canvas/api/interfaces/canvasprops/#backgroundimage) *** ### canvasColor? [#canvascolor] > `optional` **canvasColor?**: `string` Defined in: [Canvas/types.ts:113](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L113) Background color shown when no background image is configured. #### Remarks [#remarks-3] `canvasColor` is also painted underneath every JPEG export, even when a background image is included, because JPEG cannot represent transparent pixels. With `preserveBackgroundImageAspectRatio="meet"` (or any value that letterboxes the image), the letterbox regions of a JPEG export will be filled with `canvasColor`. #### Default Value [#default-value-2] `"white"` #### Inherited from [#inherited-from-2] [`CanvasProps`](/react-sketch-canvas/api/interfaces/canvasprops/).[`canvasColor`](/react-sketch-canvas/api/interfaces/canvasprops/#canvascolor) *** ### className? [#classname] > `optional` **className?**: `string` Defined in: [Canvas/types.ts:119](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L119) CSS class name applied to the outer canvas wrapper. #### Default Value [#default-value-3] `"react-sketch-canvas"` #### Inherited from [#inherited-from-3] [`CanvasProps`](/react-sketch-canvas/api/interfaces/canvasprops/).[`className`](/react-sketch-canvas/api/interfaces/canvasprops/#classname) *** ### eraserMode? [#erasermode] > `optional` **eraserMode?**: [`EraserMode`](/react-sketch-canvas/api/type-aliases/erasermode/) Defined in: [ReactSketchCanvas/types.ts:54](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/ReactSketchCanvas/types.ts#L54) Eraser behavior used when `eraseMode(true)` is active or a pen eraser button is detected. #### Remarks [#remarks-4] Use `"mask"` to preserve eraser gestures as SVG mask paths. Use `"stroke"` when erasing should delete whole drawing strokes touched by the eraser. #### Default Value [#default-value-4] `"mask"` *** ### eraserWidth? [#eraserwidth] > `optional` **eraserWidth?**: `number` Defined in: [ReactSketchCanvas/types.ts:43](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/ReactSketchCanvas/types.ts#L43) Width of eraser strokes in pixels. #### Remarks [#remarks-5] This width is used when `eraseMode(true)` is active or when a pen eraser button is detected. #### Default Value [#default-value-5] `8` *** ### exportWithBackgroundImage? [#exportwithbackgroundimage] > `optional` **exportWithBackgroundImage?**: `boolean` Defined in: [Canvas/types.ts:129](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L129) Whether exported images and SVGs include `backgroundImage`. #### Remarks [#remarks-6] Set this to `false` when the background image is only a drawing guide and should not be part of exported output. #### Default Value [#default-value-6] ```ts false ``` #### Inherited from [#inherited-from-4] [`CanvasProps`](/react-sketch-canvas/api/interfaces/canvasprops/).[`exportWithBackgroundImage`](/react-sketch-canvas/api/interfaces/canvasprops/#exportwithbackgroundimage) *** ### height? [#height] > `optional` **height?**: `string` Defined in: [Canvas/types.ts:139](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L139) CSS height of the canvas wrapper. #### Remarks [#remarks-7] Accepts any valid CSS height value, such as `"400px"`, `"60vh"`, or `"100%"`. #### Default Value [#default-value-7] `"100%"` #### Inherited from [#inherited-from-5] [`CanvasProps`](/react-sketch-canvas/api/interfaces/canvasprops/).[`height`](/react-sketch-canvas/api/interfaces/canvasprops/#height) *** ### id? [#id] > `optional` **id?**: `string` Defined in: [Canvas/types.ts:151](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L151) DOM id applied to the rendered SVG canvas. #### Remarks [#remarks-8] Internal SVG definitions such as masks and background patterns are isolated per canvas instance, so multiple canvases can use the default id without sharing those internal references. Provide a unique id when application code needs to select or label a specific canvas element. #### Default Value [#default-value-8] `"react-sketch-canvas"` #### Inherited from [#inherited-from-6] [`CanvasProps`](/react-sketch-canvas/api/interfaces/canvasprops/).[`id`](/react-sketch-canvas/api/interfaces/canvasprops/#id) *** ### onChange? [#onchange] > `optional` **onChange?**: (`updatedPaths`) => `void` Defined in: [ReactSketchCanvas/types.ts:65](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/ReactSketchCanvas/types.ts#L65) Called whenever the rendered path list changes. #### Parameters [#parameters] ##### updatedPaths [#updatedpaths] [`CanvasPath`](/react-sketch-canvas/api/interfaces/canvaspath/)\[] Complete current path list. #### Returns [#returns] `void` Nothing. #### Remarks [#remarks-9] Use this callback to persist drawings as the user sketches. The callback is invoked after strokes, undo, redo, clear, reset, and `loadPaths` updates. *** ### onStroke? [#onstroke] > `optional` **onStroke?**: (`path`, `isEraser`) => `void` Defined in: [ReactSketchCanvas/types.ts:78](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/ReactSketchCanvas/types.ts#L78) Called when the user completes a stroke. #### Parameters [#parameters-1] ##### path [#path] [`CanvasPath`](/react-sketch-canvas/api/interfaces/canvaspath/) Stroke that was just completed. ##### isEraser [#iseraser] `boolean` Whether the completed stroke erased existing content. #### Returns [#returns-1] `void` Nothing. #### Remarks [#remarks-10] This callback fires for both drawing and erasing strokes. It is intended for event-style handling; use `onChange` when you need the complete drawing state. *** ### preserveBackgroundImageAspectRatio? [#preservebackgroundimageaspectratio] > `optional` **preserveBackgroundImageAspectRatio?**: `string` Defined in: [Canvas/types.ts:161](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L161) SVG `preserveAspectRatio` value used for `backgroundImage`. #### Remarks [#remarks-11] See the MDN reference for accepted values: [https://developer.mozilla.org/docs/Web/SVG/Attribute/preserveAspectRatio](https://developer.mozilla.org/docs/Web/SVG/Attribute/preserveAspectRatio). #### Default Value [#default-value-9] `"none"` #### Inherited from [#inherited-from-7] [`CanvasProps`](/react-sketch-canvas/api/interfaces/canvasprops/).[`preserveBackgroundImageAspectRatio`](/react-sketch-canvas/api/interfaces/canvasprops/#preservebackgroundimageaspectratio) *** ### readOnly? [#readonly] > `optional` **readOnly?**: `boolean` Defined in: [Canvas/types.ts:209](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L209) Whether pointer drawing is disabled. #### Remarks [#remarks-12] Existing paths are still rendered and ref export methods still work. #### Default Value [#default-value-10] ```ts false ``` #### Inherited from [#inherited-from-8] [`CanvasProps`](/react-sketch-canvas/api/interfaces/canvasprops/).[`readOnly`](/react-sketch-canvas/api/interfaces/canvasprops/#readonly) *** ### strokeColor? [#strokecolor] > `optional` **strokeColor?**: `string` Defined in: [ReactSketchCanvas/types.ts:88](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/ReactSketchCanvas/types.ts#L88) Color used for drawing strokes. #### Remarks [#remarks-13] Accepts any SVG stroke color value, including named colors, hex colors, RGB values, and CSS variables. #### Default Value [#default-value-11] ```ts "red" ``` *** ### strokeWidth? [#strokewidth] > `optional` **strokeWidth?**: `number` Defined in: [ReactSketchCanvas/types.ts:97](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/ReactSketchCanvas/types.ts#L97) Width of drawing strokes in pixels. #### Remarks [#remarks-14] Eraser strokes use `eraserWidth` instead. #### Default Value [#default-value-12] `4` *** ### style? [#style] > `optional` **style?**: `CSSProperties` Defined in: [Canvas/types.ts:173](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L173) Inline styles applied to the outer canvas wrapper. #### Remarks [#remarks-15] The component sets `userSelect: "none"` to avoid browser selection highlights while drawing. It sets `touchAction: "none"` for touch drawing, and `touchAction: "pan-x pan-y pinch-zoom"` in pen-only mode so touch can still scroll parent containers. #### Default Value [#default-value-13] ```ts The package default canvas border style. ``` #### Inherited from [#inherited-from-9] [`CanvasProps`](/react-sketch-canvas/api/interfaces/canvasprops/).[`style`](/react-sketch-canvas/api/interfaces/canvasprops/#style) *** ### svgStyle? [#svgstyle] > `optional` **svgStyle?**: `CSSProperties` Defined in: [Canvas/types.ts:179](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L179) Inline styles applied to the internal SVG element. #### Default Value [#default-value-14] `{}` #### Inherited from [#inherited-from-10] [`CanvasProps`](/react-sketch-canvas/api/interfaces/canvasprops/).[`svgStyle`](/react-sketch-canvas/api/interfaces/canvasprops/#svgstyle) *** ### touchAction? [#touchaction] > `optional` **touchAction?**: `TouchAction` Defined in: [Canvas/types.ts:223](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L223) CSS `touch-action` applied to the canvas wrapper. #### Remarks [#remarks-16] The default is `"none"` when the canvas accepts touch drawing, so single finger gestures draw rather than scroll. Override this when you need the surrounding page to remain scrollable; for example, set `"pan-y"` to let users scroll vertically while still drawing with one finger. The browser will start a native pan only when the gesture matches the configured axis, so single-finger drawing continues to work. #### Default Value [#default-value-15] `"none"` for touch-drawing modes; `"pan-x pan-y pinch-zoom"` for pen / mouse only modes. #### Inherited from [#inherited-from-11] [`CanvasProps`](/react-sketch-canvas/api/interfaces/canvasprops/).[`touchAction`](/react-sketch-canvas/api/interfaces/canvasprops/#touchaction) *** ### width? [#width] > `optional` **width?**: `string` Defined in: [Canvas/types.ts:200](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L200) CSS width of the canvas wrapper. #### Remarks [#remarks-17] Accepts any valid CSS width value, such as `"600px"`, `"100%"`, or `"80vw"`. #### Default Value [#default-value-16] `"100%"` #### Inherited from [#inherited-from-12] [`CanvasProps`](/react-sketch-canvas/api/interfaces/canvasprops/).[`width`](/react-sketch-canvas/api/interfaces/canvasprops/#width) *** ### withTimestamp? [#withtimestamp] > `optional` **withTimestamp?**: `boolean` Defined in: [ReactSketchCanvas/types.ts:108](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/ReactSketchCanvas/types.ts#L108) Whether strokes should include start and end timestamps. #### Remarks [#remarks-18] Enable this before drawing if you want `CanvasPath.startTimestamp`, `CanvasPath.endTimestamp`, and `getSketchingTime()` to report active drawing time. #### Default Value [#default-value-17] ```ts false ``` *** ### withViewBox? [#withviewbox] > `optional` **withViewBox?**: `boolean` Defined in: [Canvas/types.ts:190](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L190) Whether the internal SVG should include a viewBox based on the latest measured canvas size. #### Remarks [#remarks-19] Enable this when you need SVG output that scales predictably with the rendered canvas dimensions. #### Default Value [#default-value-18] ```ts false ``` #### Inherited from [#inherited-from-13] [`CanvasProps`](/react-sketch-canvas/api/interfaces/canvasprops/).[`withViewBox`](/react-sketch-canvas/api/interfaces/canvasprops/#withviewbox) # ReactSketchCanvasRef (/react-sketch-canvas/api/interfaces/reactsketchcanvasref) Defined in: [ReactSketchCanvas/types.ts:120](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/ReactSketchCanvas/types.ts#L120) Imperative ref API exposed by [ReactSketchCanvas](/react-sketch-canvas/api/variables/reactsketchcanvas/). ## Remarks [#remarks] Use this ref to control drawing mode, history, exports, and path loading from parent components. ## Extends [#extends] * [`CanvasRef`](/react-sketch-canvas/api/interfaces/canvasref/) ## Properties [#properties] ### clearCanvas [#clearcanvas] > **clearCanvas**: () => `void` Defined in: [ReactSketchCanvas/types.ts:142](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/ReactSketchCanvas/types.ts#L142) Remove all paths from the canvas while preserving history. #### Returns [#returns] `void` Nothing. #### Remarks [#remarks-1] Users can still undo back to the previous drawing after `clearCanvas()`. Use `resetCanvas()` when you want to remove paths and clear undo/redo history. *** ### eraseMode [#erasemode] > **eraseMode**: (`erase`) => `void` Defined in: [ReactSketchCanvas/types.ts:131](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/ReactSketchCanvas/types.ts#L131) Switch between drawing and erasing. #### Parameters [#parameters] ##### erase [#erase] `boolean` Whether future pointer strokes should erase. #### Returns [#returns-1] `void` Nothing. #### Remarks [#remarks-2] Passing `true` enables erasing for future strokes. Passing `false` returns to normal drawing mode. Existing paths are not changed. *** ### exportImage [#exportimage] > **exportImage**: (`imageType`, `options?`) => `Promise`\<`string`> Defined in: [Canvas/types.ts:243](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L243) Export the current canvas as a raster image data URL. #### Parameters [#parameters-1] ##### imageType [#imagetype] [`ExportImageType`](/react-sketch-canvas/api/type-aliases/exportimagetype/) Image format to create. ##### options? [#options] [`ExportImageOptions`](/react-sketch-canvas/api/interfaces/exportimageoptions/) Optional export dimensions. #### Returns [#returns-2] `Promise`\<`string`> Promise that resolves to a `data:image/*` URL. #### Remarks [#remarks-3] The output includes the currently rendered strokes. Background image export depends on the `exportWithBackgroundImage` prop. #### Inherited from [#inherited-from] [`CanvasRef`](/react-sketch-canvas/api/interfaces/canvasref/).[`exportImage`](/react-sketch-canvas/api/interfaces/canvasref/#exportimage) *** ### exportPaths [#exportpaths] > **exportPaths**: () => `Promise`\<[`CanvasPath`](/react-sketch-canvas/api/interfaces/canvaspath/)\[]> Defined in: [ReactSketchCanvas/types.ts:171](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/ReactSketchCanvas/types.ts#L171) Export the current path data. #### Returns [#returns-3] `Promise`\<[`CanvasPath`](/react-sketch-canvas/api/interfaces/canvaspath/)\[]> Promise that resolves with the current path list. #### Remarks [#remarks-4] The returned paths can be stored and later passed to `loadPaths()`. *** ### exportSvg [#exportsvg] > **exportSvg**: () => `Promise`\<`string`> Defined in: [Canvas/types.ts:256](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L256) Export the current canvas as SVG markup. #### Returns [#returns-4] `Promise`\<`string`> Promise that resolves to SVG markup. #### Remarks [#remarks-5] The returned string contains the cloned SVG element after export-specific background handling has been applied. #### Inherited from [#inherited-from-1] [`CanvasRef`](/react-sketch-canvas/api/interfaces/canvasref/).[`exportSvg`](/react-sketch-canvas/api/interfaces/canvasref/#exportsvg) *** ### getSketchingTime [#getsketchingtime] > **getSketchingTime**: () => `Promise`\<`number`> Defined in: [ReactSketchCanvas/types.ts:192](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/ReactSketchCanvas/types.ts#L192) Get the total active drawing time in milliseconds. #### Returns [#returns-5] `Promise`\<`number`> Promise that resolves with the total sketching time. #### Remarks [#remarks-6] This only works when `withTimestamp` is enabled before drawing. Idle time between strokes is not included. *** ### loadPaths [#loadpaths] > **loadPaths**: (`paths`) => `void` Defined in: [ReactSketchCanvas/types.ts:182](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/ReactSketchCanvas/types.ts#L182) Append paths to the canvas. #### Parameters [#parameters-2] ##### paths [#paths] [`CanvasPath`](/react-sketch-canvas/api/interfaces/canvaspath/)\[] Paths to append to the current drawing. #### Returns [#returns-6] `void` Nothing. #### Remarks [#remarks-7] Existing paths are preserved. The provided paths are appended to the end of the current path list and become part of undo/redo history. *** ### redo [#redo] > **redo**: () => `void` Defined in: [ReactSketchCanvas/types.ts:162](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/ReactSketchCanvas/types.ts#L162) Restore the next history entry after an undo. #### Returns [#returns-7] `void` Nothing. #### Remarks [#remarks-8] Calling `redo()` when there is no later history entry leaves the canvas unchanged. *** ### resetCanvas [#resetcanvas] > **resetCanvas**: () => `void` Defined in: [ReactSketchCanvas/types.ts:202](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/ReactSketchCanvas/types.ts#L202) Remove all paths and clear undo/redo history. #### Returns [#returns-8] `void` Nothing. #### Remarks [#remarks-9] Use `clearCanvas()` instead when the user should be able to undo the clearing action. *** ### undo [#undo] > **undo**: () => `void` Defined in: [ReactSketchCanvas/types.ts:152](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/ReactSketchCanvas/types.ts#L152) Restore the previous history entry. #### Returns [#returns-9] `void` Nothing. #### Remarks [#remarks-10] Calling `undo()` when there is no earlier history entry leaves the canvas unchanged. # AllowOnlyPointerType (/react-sketch-canvas/api/type-aliases/allowonlypointertype) > **AllowOnlyPointerType** = `"all"` | `"pen"` | `"mouse"` | `"touch"` Defined in: [Canvas/types.ts:19](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/types.ts#L19) Pointer device class accepted by the drawing surface. ## Remarks [#remarks] Use `"all"` to accept mouse, pen, and touch input. Use a specific pointer type when the canvas should ignore other input devices, for example a pen-only signing flow. # EraserMode (/react-sketch-canvas/api/type-aliases/erasermode) > **EraserMode** = `"mask"` | `"stroke"` Defined in: [ReactSketchCanvas/types.ts:14](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/ReactSketchCanvas/types.ts#L14) Eraser behavior used for pointer erasing. ## Remarks [#remarks] `"mask"` stores eraser gestures as mask paths, preserving the historical export and undo/redo behavior. `"stroke"` removes whole drawing strokes touched by the eraser gesture instead of storing the gesture path. # ExportImageType (/react-sketch-canvas/api/type-aliases/exportimagetype) > **ExportImageType** = `"jpeg"` | `"png"` Defined in: [types/canvas.ts:11](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/types/canvas.ts#L11) Raster image format used by [ReactSketchCanvasRef.exportImage](/react-sketch-canvas/api/interfaces/reactsketchcanvasref/#exportimage) and [CanvasRef.exportImage](/react-sketch-canvas/api/interfaces/canvasref/#exportimage). ## Remarks [#remarks] Use `"png"` when you need transparency. Use `"jpeg"` for smaller files or when the exported image should always include a solid background color. # Canvas (/react-sketch-canvas/api/variables/canvas) > `const` **Canvas**: `ForwardRefExoticComponent`\<[`CanvasProps`](/react-sketch-canvas/api/interfaces/canvasprops/) & `RefAttributes`\<[`CanvasRef`](/react-sketch-canvas/api/interfaces/canvasref/)>> Defined in: [Canvas/index.tsx:24](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/Canvas/index.tsx#L24) Low-level SVG drawing canvas. ## Remarks [#remarks] `Canvas` renders the SVG surface, handles pointer normalization, and exposes export methods through its forwarded ref. Most consumers should use `ReactSketchCanvas` instead, which manages drawing state and undo/redo. Use `Canvas` directly when you need full control over path state, custom history behavior, or integration with an external drawing state machine. ## Param [#param] Rendering, pointer, and export options for the canvas. ## Param [#param-1] Ref exposing [CanvasRef](/react-sketch-canvas/api/interfaces/canvasref/) export methods. ## Returns [#returns] The low-level canvas element. # ReactSketchCanvas (/react-sketch-canvas/api/variables/reactsketchcanvas) > `const` **ReactSketchCanvas**: `ForwardRefExoticComponent`\<[`ReactSketchCanvasProps`](/react-sketch-canvas/api/interfaces/reactsketchcanvasprops/) & `RefAttributes`\<[`ReactSketchCanvasRef`](/react-sketch-canvas/api/interfaces/reactsketchcanvasref/)>> Defined in: [ReactSketchCanvas/index.tsx:26](https://github.com/vinothpandian/react-sketch-canvas/blob/main/packages/react-sketch-canvas/src/ReactSketchCanvas/index.tsx#L26) Stateful sketch canvas component for freehand SVG drawing. ## Remarks [#remarks] `ReactSketchCanvas` manages paths, draw/erase mode, undo/redo history, timestamp capture, and public imperative methods. It is the primary component intended for application use. Use a ref when you need to export images or paths, toggle erasing from a toolbar, or control history from parent UI. ## Param [#param] Public drawing, styling, export, and callback options. ## Param [#param-1] Ref exposing [ReactSketchCanvasRef](/react-sketch-canvas/api/interfaces/reactsketchcanvasref/) methods. ## Returns [#returns] The sketch canvas component. # Backgrounds (/react-sketch-canvas/guides/backgrounds) A background image turns the canvas into an annotation surface: mark up a photo, trace over a template, or take notes on top of an existing asset. The image stays separate from the user's strokes, so you can preserve the source and export the combined result later. ## URL image [#url-image] Pass any image URL to `backgroundImage`. Use `preserveBackgroundImageAspectRatio` to control how the image fits the canvas; the same values accepted by SVG's `preserveAspectRatio` attribute work here. ## Data URI [#data-uri] The same prop also accepts a data URI. This is useful when the image lives in memory: an uploaded file, an API response, or a generated asset. The canvas API stays the same; only the shape of the value changes. `backgroundImage` is treated as trusted. The library loads it directly into an SVG `` element, and for SVG data URIs it is parsed with `DOMParser` to read the embedded `viewBox`. Do not pass attacker-controlled strings here without validating them first. ## See also [#see-also] * [Exporting & saving](/react-sketch-canvas/guides/exporting/#exporting-with-a-background): include the background image in raster exports. # Direct Canvas usage (/react-sketch-canvas/guides/canvas) `ReactSketchCanvas` is the default component for most apps. It owns the active stroke, undo/redo history, eraser mode, and exported path state. Use `Canvas` directly when you need to control those pieces yourself. That is useful for collaborative editors, synced external state, custom history stacks, or tools where the app decides how each pointer event becomes a `CanvasPath`. ## Controlled path inspection [#controlled-path-inspection] `Canvas` can render paths owned by your app and report normalized pointer points without creating a new stroke. That makes it useful for review tools, annotation inspectors, multiplayer cursors, or any surface where pointer input selects existing data instead of drawing. ## External state machines [#external-state-machines] Because the component is controlled, you can route pointer events through a reducer, store, CRDT, or command bus before rendering paths. ```tsx twoslash title="External state machine" import React from "react"; import { Canvas, type CanvasPath, type Point } from "react-sketch-canvas"; type EditorState = { activeTool: "pen" | "eraser" | null; paths: CanvasPath[]; }; type EditorAction = | { type: "stroke.started"; point: Point; isEraser: boolean } | { type: "stroke.moved"; point: Point } | { type: "stroke.finished" }; declare const editorState: EditorState; declare const dispatch: (action: EditorAction) => void; // ---cut--- export function StateMachineCanvas() { return ( // [!code highlight] dispatch({ type: "stroke.started", point, isEraser: isEraser ?? false }) // [!code highlight] } // [!code highlight] onPointerMove={(point) => dispatch({ type: "stroke.moved", point })} // [!code highlight] onPointerUp={() => dispatch({ type: "stroke.finished" })} // [!code highlight] allowOnlyPointerType="all" backgroundImage="" canvasColor="white" exportWithBackgroundImage={false} width="100%" height="480px" style={{ border: "1px solid #d4d4d8" }} svgStyle={{}} /> ); } ``` ## Read-only or custom export surfaces [#read-only-or-custom-export-surfaces] You can also render `Canvas` as a read-only preview while another part of your app owns editing. The ref still exposes export methods, so preview panes and review screens can export the same controlled paths without enabling pointer input. ```tsx twoslash title="Read-only export preview" import React, { useRef } from "react"; import { Canvas, type CanvasPath, type CanvasRef } from "react-sketch-canvas"; declare const approvedPaths: CanvasPath[]; // ---cut--- export function ExportPreview() { const previewRef = useRef(null); return ( undefined} onPointerMove={() => undefined} onPointerUp={() => undefined} allowOnlyPointerType="all" backgroundImage="" canvasColor="white" exportWithBackgroundImage={false} width="100%" height="320px" readOnly // [!code highlight] style={{ border: "1px solid #d4d4d8" }} svgStyle={{}} /> ); } ``` # Colors & theming (/react-sketch-canvas/guides/colors-and-theming) The canvas takes color values as plain props. There is no built-in color picker. Pass `strokeColor` and `canvasColor` from your own state and the canvas re-renders when they change. ## Stroke and canvas color [#stroke-and-canvas-color] Use `strokeColor` for the pen color and `canvasColor` for the background fill. Both props accept any standard CSS color format, including: * **Hexadecimal**: `#a855f7` or `#000` * **Named colors**: `red`, `transparent`, or `currentColor` * **Functional notations**: `rgb(168 85 247)`, `rgba(0, 0, 0, 0.5)`, or `hsl(270 91% 65%)` * **CSS Variables**: `var(--stroke-color)` ```tsx twoslash title="Configuring colors" import React from "react"; import { ReactSketchCanvas } from "react-sketch-canvas"; // ---cut--- export function StyledCanvas() { return ( ); } ``` This pattern works well when color is part of a larger form, theme editor, or annotation workflow. ### Individual strokes vs. bulk recoloring [#individual-strokes-vs-bulk-recoloring] `strokeColor` is captured **at the moment each stroke is drawn**, meaning individual strokes can be colored differently. If you change `strokeColor` in your state between strokes, the user can draw a multi-colored sketch: * **Per-stroke colors**: Changing `strokeColor` only affects *new* strokes. Past strokes remain in the color they were originally drawn with. * **Bulk recoloring**: If you want to recolor *all* existing and future strokes simultaneously (for example, when switching between dark and light mode), pass a **CSS Variable** (e.g., `strokeColor="var(--stroke-color)"`) or `currentColor`. When the CSS variable or color changes in your stylesheet, all strokes using that variable will immediately update to the new color. To use bulk recoloring with CSS variables, make sure the variables are defined on a parent container of the canvas and updated when your application theme shifts. ## Dark and light mode [#dark-and-light-mode] The canvas does not switch colors automatically when your app changes theme. Pass values that reflect your app's theme state, or define CSS variables near the canvas and update those variables from your app's theme selector. The example keeps the controls styled by the documentation site, then scopes canvas-only variables on `.canvas-wrapper`. The `.dark .canvas-wrapper` selector updates only the values passed to `canvasColor` and `strokeColor`. CSS variables in `strokeColor` and `canvasColor` resolve when the canvas renders. If your theme changes without re-rendering the React component, trigger a parent re-render so the canvas reads the updated variable values. # Drawing & erasing (/react-sketch-canvas/guides/drawing-and-erasing) Most drawing tools need at least two modes: adding ink and removing it. `ReactSketchCanvas` exposes that switch through its ref, so your toolbar can stay in React while the canvas handles pointer input. ## Switching modes [#switching-modes] Call `eraseMode(true)` on the canvas ref to start erasing, and `eraseMode(false)` to return to drawing. Keep the active mode in component state so your toolbar can render the correct button as selected and show the right width control. ```tsx twoslash title="DrawingToolbar.tsx" import React, { useRef, useState } from "react"; import { ReactSketchCanvas, type ReactSketchCanvasRef, } from "react-sketch-canvas"; // ---cut--- export function DrawingToolbar() { const canvasRef = useRef(null); const [mode, setMode] = useState<"draw" | "erase">("draw"); return ( <> ); } ``` ## Eraser mode: `mask` vs `stroke` [#eraser-mode-mask-vs-stroke] The `eraserMode` prop controls how eraser gestures are stored. * `eraserMode="mask"` (default) stores each eraser gesture as a mask path. The original strokes are not changed, so undo and redo replay the exact visual state. * `eraserMode="stroke"` deletes any drawing stroke the eraser touches. There is no eraser path in the saved state. `mask` is the default for backward compatibility. Pick `stroke` only when you want erased strokes to be removed from the path list; for example, when the result will be re-serialized and edited later. ```tsx twoslash {1} title="Choose eraser behavior" import React, { useState } from "react"; import { ReactSketchCanvas, type EraserMode, } from "react-sketch-canvas"; // ---cut--- export function CanvasWithEraserModeChoice() { const [eraserMode, setEraserMode] = useState("mask"); return ( <> // ^? ); } ``` ## Stroke width [#stroke-width] `strokeWidth` and `eraserWidth` are independent. Expose two sliders if your toolbar lets users change both. If you only show one width control, swap which prop it drives based on the current mode. ## See also [#see-also] * [Colors & theming](/react-sketch-canvas/guides/colors-and-theming/): change stroke and canvas colors. * [History](/react-sketch-canvas/guides/history/): undo, redo, clear, and reset. # Exporting & saving (/react-sketch-canvas/guides/exporting) The canvas can produce three kinds of output: a raster image (PNG or JPEG), an SVG string, and the underlying path data. Pick the one that matches what you need to store, share, or restore. ## Raster export (PNG, JPEG) [#raster-export-png-jpeg] Call `exportImage("png")` or `exportImage("jpeg")`. The method returns a `Promise` that resolves to a data URL. ```tsx twoslash title="Export to PNG" import React, { useRef } from "react"; import { ReactSketchCanvas, type ReactSketchCanvasRef, } from "react-sketch-canvas"; // ---cut--- export function ExportButton() { const canvasRef = useRef(null); return ( <> ); } ``` ## SVG export [#svg-export] `exportSvg()` returns a `Promise` with the SVG markup. Use this when you want a vector output you can embed elsewhere, or process server-side. ```tsx twoslash import { type ReactSketchCanvasRef } from "react-sketch-canvas"; declare const canvasRef: React.RefObject; // ---cut--- const svg = await canvasRef.current?.exportSvg(); ``` ## Save and load [#save-and-load] To persist a drawing and restore it later, work with the path data directly. `exportPaths()` returns the array of `CanvasPath` objects the canvas is rendering. `loadPaths()` accepts that same shape. ```tsx twoslash title="Round-trip save and load" import React, { useRef } from "react"; import { ReactSketchCanvas, type CanvasPath, type ReactSketchCanvasRef, } from "react-sketch-canvas"; // ---cut--- export function SaveLoad() { const canvasRef = useRef(null); const save = async () => { const paths = (await canvasRef.current?.exportPaths()) ?? []; // [!code highlight] localStorage.setItem("sketch", JSON.stringify(paths)); }; const load = () => { const raw = localStorage.getItem("sketch"); if (!raw) return; const paths = JSON.parse(raw) as CanvasPath[]; canvasRef.current?.loadPaths(paths); // [!code highlight] }; return ( <> ); } ``` `loadPaths()` appends to the existing strokes. Call `resetCanvas()` first if you want to replace the current drawing instead of adding to it. ## Exporting with a background [#exporting-with-a-background] Set `exportWithBackgroundImage` on the canvas to include the configured `backgroundImage` in raster exports. Use this when consumers need a PNG or JPEG that shows both the drawing and the background. Raster export with a remote background can fail at runtime. The export rejects with a distinct error for each failure mode: cross-origin (CORS), data URI decode, and same-origin "not reachable". Catch the rejection and show an appropriate fallback to the user. JPEG exports always paint `canvasColor` as the base because JPEG has no transparent pixels. When `preserveBackgroundImageAspectRatio` letterboxes the background, the letterbox regions in a JPEG export will be `canvasColor`. PNG exports keep those regions transparent unless the background fully covers the canvas. ## Raster quality and pixel ratio [#raster-quality-and-pixel-ratio] `exportImage()` accepts an optional `{ width, height }` second argument. With no second argument, the output is scaled by `window.devicePixelRatio` so it stays sharp on high-DPI screens. With explicit dimensions, the result is exactly that many pixels, which is what you want for fixed-size assets like thumbnails, social cards, or print previews. A common pattern for "crisp, fixed logical size" output is to multiply your logical CSS dimensions by a target pixel ratio: ```tsx twoslash import { type ReactSketchCanvasRef } from "react-sketch-canvas"; declare const canvasRef: React.RefObject; // ---cut--- const logicalWidth = 640; const logicalHeight = 360; const pixelRatio = 2; const dataUrl = await canvasRef.current?.exportImage("png", { width: logicalWidth * pixelRatio, height: logicalHeight * pixelRatio, }); ``` # History (/react-sketch-canvas/guides/history) Drawing interfaces need escape hatches. Users should be able to undo a shaky stroke, redo an action they changed their mind about, and clear or reset the canvas when they want to start over. The canvas exposes these as ref methods. Your toolbar stays as ordinary React UI; the methods act on the canvas's internal history. ## Undo and redo [#undo-and-redo] `undo()` removes the most recent stroke. `redo()` puts it back. Both are safe to call when there's nothing to undo or redo; they are no-ops. ## Scrub through saved strokes [#scrub-through-saved-strokes] `exportPaths()` returns an ordered list of strokes. If you save that list, you can replay the drawing by loading the first stroke, then the first two strokes, and so on. This example loads the paths from `initialSketch.json` and uses a slider to choose how many saved strokes are visible. ## Clear vs reset [#clear-vs-reset] These two methods look similar but differ in one important way. * `clearCanvas()` removes the visible paths while keeping the canvas ready for more drawing. Undo can still bring strokes back. * `resetCanvas()` returns the canvas to its initial state. Use it when you have loaded paths or a preconfigured example and want a true blank slate. When replacing a drawing loaded with `loadPaths()`, call `resetCanvas()` first. See [Exporting & saving](/react-sketch-canvas/guides/exporting/#save-and-load). `resetCanvas()` is destructive. The history is cleared, so undo will not bring strokes back after a reset. Prompt the user if losing the drawing would be unexpected. ```tsx twoslash title="HistoryToolbar.tsx" import React, { useRef } from "react"; import { ReactSketchCanvas, type ReactSketchCanvasRef, } from "react-sketch-canvas"; // ---cut--- export function HistoryToolbar() { const canvasRef = useRef(null); return ( <> ); } ``` # Installation (/react-sketch-canvas/guides/installation) `react-sketch-canvas` is a single npm package. It renders an SVG drawing surface, so there is no extra canvas runtime or browser plugin to configure. ## Install [#install] ```sh npm install react-sketch-canvas ``` ```sh yarn add react-sketch-canvas ``` ```sh pnpm add react-sketch-canvas ``` ## Quick start [#quick-start] ### Import the component [#import-the-component] ```tsx twoslash import { ReactSketchCanvas } from "react-sketch-canvas"; ``` ### Render it with the props you care about [#render-it-with-the-props-you-care-about] Width, height, stroke color, and canvas color are the most common starting props. ```tsx twoslash title="App.tsx" import React from "react"; import { ReactSketchCanvas } from "react-sketch-canvas"; // ---cut--- export function App() { return ( ); } ``` ### Try it [#try-it] ## What's next [#whats-next] * Build a toolbar that switches between drawing and erasing. See [Drawing & erasing](/react-sketch-canvas/guides/drawing-and-erasing/). * Wire undo, redo, clear, and reset to your own controls. See [History](/react-sketch-canvas/guides/history/). * Export the drawing or save it for later. See [Exporting & saving](/react-sketch-canvas/guides/exporting/). # Layout (/react-sketch-canvas/guides/layout) `ReactSketchCanvas` reads pointer events in viewport-relative coordinates and subtracts the canvas's own `getBoundingClientRect()`. Both values update together when the page scrolls. They also update when an ancestor element scrolls or a CSS transform moves the canvas. Strokes land where the pointer is, no matter how the canvas is laid out. These three demos cover the layout patterns most likely to cause coordinate drift in other canvas libraries. ## Scrollable parent [#scrollable-parent] A common layout puts the canvas inside an `overflow-y: auto` container (a side panel, a fixed-height annotation viewport). Whenever that container scrolls, `clientX/clientY` and `getBoundingClientRect()` both reflect the new viewport position, so the canvas-relative point stays correct. Scroll the container, then draw. Every stroke lands exactly where the pointer is, including immediately after a scroll. ## Nested scroll containers [#nested-scroll-containers] Real layouts often have more than one scroll axis (a horizontally scrolling panel inside a vertically scrolling page). Reading viewport-relative coordinates makes the canvas immune to any number of scrolling ancestors: only the immediate `getBoundingClientRect()` matters, and the browser already accounts for every ancestor in that rectangle. Scroll the outer container horizontally and the inner container vertically, then draw. Strokes land on the pointer regardless of either scroll position. ## Scaled parent [#scaled-parent] When an ancestor uses `transform: scale()`, the canvas renders at the scaled size. Its on-screen position still comes from `getBoundingClientRect()`, which reports the post-transform rectangle. Pointer events arrive in the same post-transform space, so the visible stroke stays under the pointer at any zoom level. Drag the slider to scale the wrapper between 0.5× and 1.5×, then draw at each size. # Performance (/react-sketch-canvas/guides/performance) The canvas is built to stay usable with dense SVG drawings. The internal renderer batches points within a stroke, and SVG path data is cheap for the browser to update. ## Stress test [#stress-test] The demo below adds up to 1,000 strokes at a time, with up to 1,000 random points per stroke. Add pen strokes for heavy path rendering, then add eraser masks to exercise the masking pipeline. The counter shows the total strokes and points held by the canvas. ## Tips [#tips] * **Avoid re-rendering the canvas on every stroke.** Keep your toolbar state outside the same component subtree if possible, or memoize the toolbar so a new stroke does not re-render the buttons. * **Batch `loadPaths()` calls.** Passing all paths in a single call is much cheaper than appending one stroke at a time. * **Drop timestamps when you don't need them.** `withTimestamp` records two `Date.now()` calls per stroke and slightly increases the size of saved data. * **Cap the number of points per stroke if your input source is high-frequency.** The default pointer event rate is fine; synthetic input streams may need throttling. # Restricting pointer input (/react-sketch-canvas/guides/pointer-input) By default, `ReactSketchCanvas` accepts every pointer type the browser reports. That is the right default for most cases. Production interfaces often need tighter control; for example, a stylus-first note app may want to ignore finger touches so users can rest their hand on a tablet. Use the `allowOnlyPointerType` prop to restrict input. ## Options [#options] * `all` (default): every pointer device draws. * `pen`: only pen input, including stylus, Apple Pencil, Wacom, Surface Pen. * `mouse`: only mouse input. * `touch`: only finger touch. ## Try each mode [#try-each-mode] The default. Every supported pointer type draws. Best for stylus-first experiences: tablet annotation, handwriting, signature flows where accidental touch marks are costly. Useful for desktop-only drawing areas: admin tools, demos, or test fixtures where touch and pen input would muddy the interaction. Focused on mobile and kiosk-style experiences where finger input is the only expected input. The browser decides which pointer type each event belongs to. Some devices report pen events that look like mouse events, and vice versa. Test on real hardware before shipping a restricted canvas to production. # Read-only mode (/react-sketch-canvas/guides/read-only) Sometimes a drawing should be visible but not editable: a submitted signature, a saved sketch, an annotation in review. Pass `readOnly` to display the canvas without accepting pointer input. ## Using `readOnly` [#using-readonly] Set the prop to `true`. The canvas keeps rendering the current paths but ignores all pointer events. You don't need a separate viewer component. ```tsx twoslash title="ReadOnlyView.tsx" import React from "react"; import { ReactSketchCanvas } from "react-sketch-canvas"; // ---cut--- export function ReadOnlyView() { return ; // [!code highlight] } ``` ## Pairing with loaded paths [#pairing-with-loaded-paths] `readOnly` is most useful with saved drawings loaded via `loadPaths()`. See [Exporting & saving](/react-sketch-canvas/guides/exporting/#save-and-load) for the full round-trip. Toggling `readOnly` does not clear the canvas. The drawing remains visible whether or not new input is accepted. # Sketching time (/react-sketch-canvas/guides/sketching-time) Some products need more than the final drawing. You may also need to know how long the user spent actively sketching, signing, or annotating. The canvas can record per-stroke timestamps and report total active time on demand. ## Enabling timestamps [#enabling-timestamps] Pass `withTimestamp` to the canvas. Every stroke is recorded with start and end times. Call `getSketchingTime()` on the ref to read the total active time in milliseconds; idle moments between strokes are not counted. ```tsx twoslash title="Read total sketching time" import React, { useRef, useState } from "react"; import { ReactSketchCanvas, type ReactSketchCanvasRef, } from "react-sketch-canvas"; // ---cut--- export function TimedCanvas() { const canvasRef = useRef(null); const [ms, setMs] = useState(0); return ( <> // [!code highlight]

{ms} ms

); } ``` `withTimestamp` must be set before strokes are drawn. Enabling it later does not retroactively add timestamps to existing strokes, and `getSketchingTime()` will return 0 for any stroke that does not have them. # React Sketch Canvas (/react-sketch-canvas/) React Sketch Canvas gives you a drawing surface that stores every stroke as SVG path data, so signatures, annotations, whiteboards, and review screens can be saved, replayed, scaled, and exported cleanly. You render a canvas, pass the drawing props you care about, and build the surrounding toolbar in React. The canvas handles pointer input and stroke history; your app decides how drawing fits into the product. ## Why SVG? [#why-svg] Traditional `` drawing is pixel-based. That is useful for painting apps, but it can be limiting when you need to store strokes, scale drawings, or export clean results later. React Sketch Canvas records each stroke as path data. You can load those paths back into the canvas, export them as SVG, or render the same drawing at different sizes without the blurry edges that come from bitmap scaling. ## Explore the guides [#explore-the-guides] Start with the smallest useful setup, then add the parts most production drawing surfaces need: a toolbar, undo history, input restrictions, image backgrounds, and export. Install the package and render your first canvas. Switch modes from your own toolbar and choose how the eraser behaves. Wire undo, redo, clear, and reset into your own controls. Limit drawing to mouse, touch, pen, or accept every pointer type. Draw on top of a URL or data URI image. Produce PNG, JPEG, or SVG output, or save and reload path data. ## Common use cases [#common-use-cases] * Signature capture for forms, approvals, and consent flows. * Image annotation tools for screenshots, photos, documents, and maps. * Sketch pads for education, collaboration, and lightweight whiteboarding. * Review screens where a saved drawing should be visible but not editable. * Drawing inputs that must prefer a stylus, ignore touch, or support every pointer device. ## Using AI assistants [#using-ai-assistants] If you are pairing with Claude, Cursor, Copilot, Codex, or any other LLM-powered editor, point it at the machine-readable docs so it pulls the right APIs the first time. * [`/llms.txt`](/react-sketch-canvas/llms.txt): site map of every docs page. * [`/llms-full.txt`](/react-sketch-canvas/llms-full.txt): the full documentation bundled into a single file. See the [AI assistants guide](/react-sketch-canvas/agentic-tools) for tool-specific setup. *** ReactSketchCanvas v8 was also developed using AI coding assistants. See the [AI assistants guide](/react-sketch-canvas/agentic-tools#project-note) for the project note and workflow references.