usePaint
Hook that allows you to draw in a specific area
elements
low
test coverage
Last changed: 3 days ago
Installation
Library
CLI
Manual
typescript
import { usePaint } from '@siberiacancode/reactuse';Usage
typescript
const paint = usePaint(canvasRef, { color: 'red', radius: 10 });
// or
const { ref, draw, clear, undo, redo, changeColor } = usePaint({ color: 'red', radius: 10 }, { smooth: true });Demo
Api
Parameters
| Name | Type | Default | Note |
|---|---|---|---|
| target | HookTarget | - | The target element to be painted |
| initialValue? | UsePaintInitialValue | - | The initial value of the paint |
| options? | UsePaintOptions | - | The options to be used |
Returns
UsePaintReturn
Parameters
| Name | Type | Default | Note |
|---|---|---|---|
| initialValue? | UsePaintInitialValue | - | The initial value of the paint |
| options? | UsePaintOptions | - | The options to be used |
Returns
UsePaintReturn & { ref: StateRef<HTMLCanvasElement> }
Type declaration
typescript
import type { HookTarget } from '@/utils/helpers';
import type { StateRef } from '../useRefState/useRefState';
export interface Point {
x: number;
y: number;
}
export interface Line {
color: string;
opacity: number;
points: Point[];
radius: number;
}
export interface UsePaintInitialValue {
/** The initial brush color */
color?: string;
/** The initial lines */
lines?: Line[];
/** The initial brush opacity */
opacity?: number;
/** The initial brush radius */
radius?: number;
}
export interface UsePaintOptions {
/** Whether the brush movement is smooth */
smooth?: boolean;
/** The callback when the mouse is down */
onMouseDown?: (event: MouseEvent, paint: Paint) => void;
/** The callback when the mouse is moved */
onMouseMove?: (event: MouseEvent, paint: Paint) => void;
/** The callback when the mouse is up */
onMouseUp?: (event: MouseEvent, paint: Paint) => void;
}
export interface UsePaintReturn {
/** Whether redo is available */
canRedo: boolean;
/** Whether undo is available */
canUndo: boolean;
/** The current brush color */
color: string;
/** Whether the user is drawing */
drawing: boolean;
/** The current lines */
lines: Line[];
/** The current brush opacity */
opacity: number;
/** The current brush radius */
radius: number;
/** Changes the brush color */
changeColor: (color: string) => void;
/** Changes the brush opacity */
changeOpacity: (opacity: number) => void;
/** Changes the brush radius */
changeRadius: (radius: number) => void;
/** Clears the canvas */
clear: () => void;
/** Draws a line */
draw: (line: Line) => void;
/** Redoes the last undone line */
redo: () => void;
/** Undoes the last line */
undo: () => void;
}
export interface UsePaint {
(
target: HookTarget,
initialValue?: UsePaintInitialValue,
options?: UsePaintOptions
): UsePaintReturn;
<Target extends HTMLCanvasElement>(
initialValue?: UsePaintInitialValue,
options?: UsePaintOptions
): UsePaintReturn & { ref: StateRef<Target> };
}Source
Source • DemoContributors
D
H
V