Skip to content

usePaint ​

Hook that allows you to draw in a specific area

browser
test coverage
Last changed: last month

Installation ​

Library
CLI
Manual
typescript
import { usePaint } from '@siberiacancode/reactuse';

Usage ​

typescript
const drawing = usePaint(canvasRef);
// or
const { ref, drawing } = usePaint();

Demo ​

Api ​

Parameters

NameTypeDefaultNote
targetHookTarget-The target element to be painted
options?UsePaintOptions-The options to be used

Returns

UsePaintReturn

Parameters

NameTypeDefaultNote
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 UsePaintOptions {
  /** Brush color */
  color?: string;
  /** Initial lines */
  initialLines?: Paint['lines'];
  /** Brush opacity */
  opacity?: number;
  /** Brush radius */
  radius?: number;
  /** Smooth brush movement */
  smooth?: boolean;
  /** Callback when the mouse is down */
  onMouseDown?: (event: MouseEvent, paint: Paint) => void;
  /** Callback when the mouse is moved */
  onMouseMove?: (event: MouseEvent, paint: Paint) => void;
  /** Callback when the mouse is up */
  onMouseUp?: (event: MouseEvent, paint: Paint) => void;
}

export interface UsePaintReturn {
  drawing: boolean;
  lines: Paint['lines'];
  clear: () => void;
  draw: (points: Point[], color: string, opacity: number, radius: number) => void;
  undo: () => void;
}

export interface UsePaint {
  (target: HookTarget, options?: UsePaintOptions): UsePaintReturn;

  <Target extends HTMLCanvasElement>(
    options?: UsePaintOptions,
    target?: never
  ): UsePaintReturn & { ref: StateRef<Target> };
}

Source ​

Source • Demo

Contributors ​

D
debabin
debabin
H
hywax
hywax
V
VladPorvin
VladPorvin

Released under the MIT License.