react-signature-canvas

repository·main·Indexed 20 days ago

https://github.com/agilgur5/react-signature-canvas

A React wrapper component around the signature_pad library for capturing handwritten signatures. It provides a customizable canvas element with support for pen styles, data export via data URLs or point groups, and automatic resizing. The component exposes an imperative API via refs, including methods like clear(), isEmpty(), and getTrimmedCanvas() to remove whitespace from the signature.

Tokens
2K
Snippets
4
Records
9
Agent score
21%

What's inside react-signature-canvas

  1. Access SignatureCanvas API methods via refs

    main

    To use the component's imperative API methods, you must create a ref and attach it to the SignatureCanvas component.

    import React, { useRef } from 'react'
    import SignatureCanvas from 'react-signature-canvas'
    
    function MyApp() {
      const sigCanvas = useRef(null);
    
      // You can now call methods on sigCanvas.current
      const handleClear = () => sigCanvas.current.clear();
    
      return <SignatureCanvas ref={sigCanvas} />
    }
    import React, { useRef } from 'react'
    import SignatureCanvas from 'react-signature-canvas'
    
    function MyApp() {
      const sigCanvas = useRef(null);
    
      return <SignatureCanvas ref={sigCanvas} />
    }
  2. Access the SignatureCanvas instance methods

    main

    To interact with the signature pad (e.g., to clear the canvas or export the image), you must use a React ref to access the SignatureCanvas component instance.

    Available Methods

    SignaturePad Passthrough Methods

    • clear(): Clears the canvas.
    • isEmpty(): Returns true if the canvas is empty.
    • fromDataURL(dataURL, options): Loads a signature from a data URL.
    • toDataURL(type, encoderOptions): Returns the signature as a data URL.
    • fromData(pointGroups): Loads a signature from point data.
    • toData(): Returns the signature as point data.
    • on(event, callback): Adds an event listener.
    • off(event, callback): Removes an event listener.

    Wrapper Methods

    • getCanvas(): Returns the raw HTMLCanvasElement.
    • getTrimmedCanvas(): Returns a new HTMLCanvasElement containing only the drawn signature (trimmed of whitespace).
    • getSignaturePad(): Returns the internal SignaturePad instance.
    import React, { useRef } from 'react';
    import SignatureCanvas from 'react-signature-canvas';
    
    const MyComponent = () => {
      const sigCanvas = useRef<SignatureCanvas>(null);
    
      const clear = () => {
        sigCanvas.current?.clear();
      };
    
      const save = () => {
        if (sigCanvas.current) {
          const dataURL = sigCanvas.current.toDataURL();
          console.log(dataURL);
        }
      };
    
      return (
        <div>
          <SignatureCanvas 
            ref={sigCanvas} 
            canvasProps={{ width: 500, height: 200, className: 'sigCanvas' }} 
          />
          <button onClick={clear}>Clear</button>
          <button onClick={save}>Save</button>
        </div>
      );
    };
  3. Basic usage of SignatureCanvas

    main

    Import SignatureCanvas and render it within your React application. You can pass penColor to style the stroke and canvasProps to configure the underlying HTML5 <canvas> element (such as width, height, or CSS classes).

    import React from 'react'
    import { createRoot } from 'react-dom/client'
    import SignatureCanvas from 'react-signature-canvas'
    
    createRoot(
      document.getElementById('my-react-container')
    ).render(
      <SignatureCanvas penColor='green'
        canvasProps={{width: 500, height: 200, className: 'sigCanvas'}} />,
    )
  4. Reference SignatureCanvas API methods

    main

    The following methods are available on the SignatureCanvas instance via a ref. Most are wrappers around the signature_pad API.

    • isEmpty(): boolean — Returns whether the canvas is empty.
    • clear(): void — Clears the canvas using the backgroundColor prop.
    • fromDataURL(base64String, options): void — Writes a base64 image to the canvas.
    • toDataURL(mimetype, encoderOptions): base64string — Returns the signature image as a data URL.
    • fromData(pointGroupArray): void — Draws signature image from an array of point groups.
    • toData(): pointGroupArray — Returns signature image as an array of point groups.
    • off(): void — Unbinds all event handlers (and the window resize handler).
    • on(): void — Rebinds all event handlers (and the window resize handler).
    • getCanvas(): canvas — Returns the underlying HTML <canvas> element.
    • getTrimmedCanvas(): canvas — Returns a copy of the canvas with all whitespace removed.
    • getSignaturePad(): SignaturePad — Returns the underlying signature_pad instance.
  5. Configure SignatureCanvas props

    main

    The SignatureCanvas component accepts several optional props to control the pen stroke and canvas behavior. Most pen-related props are passed directly to the underlying signature_pad instance.

    Pen Stroke Props

    • velocityFilterWeight: number (default: 0.7)
    • minWidth: number (default: 0.5)
    • maxWidth: number (default: 2.5)
    • minDistance: number (default: 5)
    • dotSize: number | function (default: () => (this.minWidth + this.maxWidth) / 2)
    • penColor: string (default: 'black')
    • throttle: number (default: 16)

    Event Callbacks

    • onEnd: function (called when a stroke ends)
    • onBegin: function (called when a stroke begins)

    Canvas Control Props

    • canvasProps: object (properties passed directly to the <canvas /> element)
    • backgroundColor: string (default: 'rgba(0,0,0,0)'; used by the clear() method)
    • clearOnResize: boolean (default: true; whether to clear the canvas when the window resizes)
  6. SignatureCanvas Props Reference

    main

    The following props are supported by SignatureCanvas. Note that many are passed directly to the underlying signature_pad instance.

    PropTypeDescription
    velocityFilterWeightnumberWeight of the velocity filter
    minWidthnumberMinimum width of the line
    maxWidthnumberMaximum width of the line
    minDistancenumberMinimum distance between points
    dotSizenumber | FunctionSize of the dot
    penColorstringColor of the pen
    throttlenumberThrottle rate
    onEndFunctionCallback when the signature ends
    onBeginFunctionCallback when the signature begins
    canvasPropsObjectStandard HTML canvas attributes
    clearOnResizebooleanWhether to clear canvas on resize (default: true)
  7. SignatureCanvas component

    main

    The SignatureCanvas component is a React wrapper around the signature_pad library. It provides a canvas element for capturing signatures and exposes methods to interact with the underlying signature pad instance.

    Key Features

    • Automatic Resizing: Handles canvas scaling based on devicePixelRatio to ensure high-quality signatures.
    • Canvas Trimming: Includes a getTrimmedCanvas() method to return a version of the canvas with empty space removed.
    • Signature Pad API Passthrough: Most methods from the original signature_pad library are available directly on the component instance.
  8. SignatureCanvasProps interface

    main

    The SignatureCanvasProps interface defines the configuration for the SignatureCanvas component. It extends SignaturePad.SignaturePadOptions, meaning all options available to the underlying signature_pad library are valid props, plus two React-specific props:

    • canvasProps: An object containing React.CanvasHTMLAttributes<HTMLCanvasElement>. Use this to pass standard HTML canvas attributes like width, height, className, or style.
    • clearOnResize: A boolean that determines whether the canvas should be cleared when the window is resized. Defaults to true.