Signature Pad

repository·master·Indexed 11 days ago

https://github.com/szimek/signature_pad

A lightweight, HTML5 canvas-based JavaScript library for drawing smooth, variable-width signatures using Bézier curve interpolation. Version 5.1.4 supports exporting signatures as images or SVG via toDataURL() and toSVG(), and importing them via fromDataURL() or fromData(). It works across modern desktop and mobile browsers without external dependencies.

Tokens
3.1K
Snippets
18
Records
18
Agent score
94%

What's inside Signature Pad

  1. Handle high DPI screens

    master

    To prevent blurry signatures on high-resolution (Retina) screens, you must scale the canvas based on devicePixelRatio. This ensures the drawing surface matches the physical pixel density.

    function resizeCanvas() {
        const ratio =  Math.max(window.devicePixelRatio || 1, 1);
        canvas.width = canvas.offsetWidth * ratio;
        canvas.height = canvas.offsetHeight * ratio;
        canvas.getContext("2d").scale(ratio, ratio);
        signaturePad.clear(); // otherwise isEmpty() might return incorrect value
    }
    
    window.addEventListener("resize", resizeCanvas);
    resizeCanvas();
  2. Install Signature Pad

    master

    You can install the latest release using npm or Yarn, or include it directly in your HTML via a CDN script tag. The library is provided as both UMD and ES6 modules.

    npm install --save signature_pad
    yarn add signature_pad
    <script src="https://cdn.jsdelivr.net/npm/signature_pad@[version]/dist/signature_pad.umd.min.js"></script>
  3. Initialize SignaturePad

    master

    To use the library, select a <canvas> element from the DOM and pass it to the SignaturePad constructor. You can optionally provide an options object during initialization.

    const canvas = document.querySelector("canvas");
    const signaturePad = new SignaturePad(canvas);
  4. Configure SignaturePad options

    master

    Options can be set during initialization or updated at runtime by assigning values directly to the instance properties.

    // During initialization
    const signaturePad = new SignaturePad(canvas, {
        minWidth: 5,
        maxWidth: 10,
        penColor: "rgb(66, 133, 244)"
    });
    
    // During runtime
    signaturePad.minWidth = 5;
    signaturePad.penColor = "black";
  5. Manage canvas state and events

    master

    Use clear() to wipe the canvas, redraw() to refresh the drawing, and isEmpty() to check if any strokes have been made. You can also listen to stroke lifecycle events using addEventListener.

    signaturePad.clear();
    signaturePad.isEmpty();
    signaturePad.redraw();
    
    // Event listeners
    signaturePad.addEventListener("beginStroke", () => {
      console.log("Signature started");
    });
  6. Export signatures as images or SVG

    master

    Use toDataURL() to get a base64 encoded image string (PNG, JPEG, etc.) or toSVG() to get an SVG string. These are useful for saving the signature to a database or displaying it later.

    // Save as PNG
    signaturePad.toDataURL(); 
    
    // Save as JPEG with 0.5 quality
    signaturePad.toDataURL("image/jpeg", 0.5); 
    
    // Save as SVG string
    signaturePad.toSVG(); 
    
    // Save as SVG with background color included
    signaturePad.toSVG({includeBackgroundColor: true});
  7. Import signatures from Data URLs or Point Groups

    master

    You can redraw a signature using fromDataURL() (from a base64 image string) or fromData() (from the internal point group array).

    Note: fromDataURL does not populate the internal data structure, so subsequent calls to toData() will not work correctly after using it.

    // From a Data URL
    signaturePad.fromDataURL("data:image/png;base64,iVBORw0K...");
    
    // From internal point groups
    const data = signaturePad.toData();
    signaturePad.fromData(data);
    
    // From point groups without clearing existing drawing
    signaturePad.fromData(data, { clear: false });
  8. Configure SignaturePad options

    master

    The Options object allows you to customize the drawing behavior and appearance. Note that many properties can also be set per-stroke via PointGroupOptions when using fromData.

    interface Options extends Partial<PointGroupOptions> {
      minDistance?: number; // in pixels
      backgroundColor?: string; // CSS color string
      throttle?: number; // in milliseconds
      canvasContextOptions?: CanvasRenderingContext2DSettings;
    }
    
    interface PointGroupOptions {
      dotSize: number;
      minWidth: number;
      maxWidth: number;
      penColor: string;
      velocityFilterWeight: number;
      compositeOperation: GlobalCompositeOperation;
    }
  9. Reference: SignaturePad Events

    master

    Events that can be attached via addEventListener.

    beginStroke: Triggered before stroke begins. Can be canceled with event.preventDefault().
    endStroke: Triggered after stroke ends.
    beforeUpdateStroke: Triggered before stroke update.
    afterUpdateStroke: Triggered after stroke update.
  10. Reference: SignaturePad Options

    master

    The following options control the appearance and behavior of the drawing surface.

    dotSize: (float or function) Radius of a single dot. Also the width of the start of a mark.
    minWidth: (float) Minimum width of a line. Defaults to 0.5.
    maxWidth: (float) Maximum width of a line. Defaults to 2.5.
    throttle: (integer) Draw the next point at most once per every x milliseconds. Set it to 0 to turn off throttling. Defaults to 16.
    minDistance: (integer) Add the next point only if the previous one is farther than x pixels. Defaults to 5.
    backgroundColor: (string) Color used to clear the background. Defaults to "rgba(0,0,0,0)".
    penColor: (string) Color used to draw the lines. Defaults to "black".
    velocityFilterWeight: (float) Weight used to modify new velocity based on the previous velocity. Defaults to 0.7.
    canvasContextOptions: (CanvasRenderingContext2DSettings) Part of the Canvas API.
  11. Use the BasicPoint and Point interfaces for signature data

    master

    The BasicPoint interface and Point class define the structure for individual points used within the signature pad, for example when using the SignaturePad#fromData method.

    BasicPoint is a lightweight interface representing a coordinate with pressure and timestamp. Point is the concrete implementation that includes utility methods for distance, equality, and velocity calculations.

    BasicPoint Interface

    • x: The x-coordinate.
    • y: The y-coordinate.
    • pressure: The pressure applied at this point.
    • time: The timestamp of the point.

    Point Class Methods

    • distanceTo(start: BasicPoint): Returns the Euclidean distance between this point and another BasicPoint.
    • equals(other: BasicPoint): Returns true if all properties (x, y, pressure, time) are identical.
    • velocityFrom(start: BasicPoint): Returns the velocity (distance/time) between this point and a starting BasicPoint. Returns 0 if the timestamps are identical.
    import { Point, BasicPoint } from 'signature_pad';
    
    // Creating a new Point
    const p1 = new Point(10, 20, 0.5, Date.now());
    const p2 = new Point(15, 25, 0.8, Date.now() + 100);
    
    // Using utility methods
    const distance = p2.distanceTo(p1);
    const velocity = p2.velocityFrom(p1);
    const isSame = p1.equals(p2);
  12. Export signature to SVG string

    master

    The toSVG() method generates a raw SVG string representing the signature. You can include the background color or a data URL of the original image in the resulting SVG.

    const svgString = signaturePad.toSVG({
      includeBackgroundColor: true,
      includeDataUrl: false
    });