### Install with NPM Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/00-api-overview.md Use this command to install Signature Pad using the Node Package Manager. ```bash npm install signature_pad ``` -------------------------------- ### BasicPoint Example Usage Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/04-types.md Demonstrates how to create a BasicPoint object and access point data from SignaturePad's output. ```typescript const point: BasicPoint = { x: 150.5, y: 250.8, pressure: 0.75, time: 1625097600000 }; const data = signaturePad.toData(); const firstPoint: BasicPoint = data[0].points[0]; ``` -------------------------------- ### PointGroupOptions Example: Constructor Configuration Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/04-types.md Shows how to initialize SignaturePad with custom drawing options using the PointGroupOptions interface. ```typescript const options: PointGroupOptions = { dotSize: 2, minWidth: 1, maxWidth: 5, penColor: "blue", velocityFilterWeight: 0.7, compositeOperation: "source-over" }; const pad = new SignaturePad(canvas, options); ``` -------------------------------- ### Install Signature Pad with npm Source: https://github.com/szimek/signature_pad/blob/master/README.md Use npm to install the latest release of Signature Pad. This is the recommended method for project integration. ```bash npm install --save signature_pad ``` -------------------------------- ### BasicPoint Example Usage Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/02-point-classes.md Demonstrates how to create an object conforming to the BasicPoint interface. Ensure all properties are correctly typed and populated. ```typescript const point: BasicPoint = { x: 100, y: 50, pressure: 0.8, time: 1625097600000 }; ``` -------------------------------- ### Throttle Behavior Example Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/06-throttle-utility.md Illustrates the behavior of the throttle function using a timeline example, showing how calls are executed immediately on the first invocation and then only after the specified wait time has passed for subsequent calls. ```APIDOC ## Throttle Behavior Timeline ### Description Demonstrates the execution pattern of the throttle function with a trailing edge strategy. The first call executes immediately, and subsequent calls within the wait period are queued and executed after the wait time elapses. ### Example Given `wait = 16` milliseconds: ``` Time: 0ms 5ms 10ms 15ms 16ms 20ms 25ms 30ms Call: ✓ ✗ ✗ ✗ ✗ ✓ ✗ ✗ ↑ ↑ Immediate After wait ms ``` - **0ms:** Function called → executes immediately. - **5ms, 10ms, 15ms:** Function called → queued, not executed. - **16ms:** Time window elapsed → queued call executes. - **20ms:** Function called → executes immediately (new window). - **25ms, 30ms:** Function called → queued, not executed. ``` -------------------------------- ### Initialize Signature Pad and Basic Usage Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/README.md Demonstrates how to initialize SignaturePad with custom options and perform basic operations like getting data, image URLs, listening to events, and clearing the canvas. ```javascript import SignaturePad from 'signature_pad'; const canvas = document.querySelector('canvas'); const pad = new SignaturePad(canvas, { minWidth: 1, maxWidth: 5, penColor: 'black', backgroundColor: 'white' }); // Get data const data = pad.toData(); // Get image const imageUrl = pad.toDataURL('image/png'); // Listen to events pad.addEventListener('endStroke', () => { console.log('Stroke complete'); }); // Clear pad.clear(); ``` -------------------------------- ### Point Class Creation Examples Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/02-point-classes.md Shows how to instantiate the Point class with all parameters, minimal parameters, and demonstrates error handling for invalid input. The constructor validates that x and y are not NaN. ```typescript // Valid point creation const point = new Point(100, 50, 0.8, 1625097600000); // Minimal creation (pressure and time optional) const point2 = new Point(100, 50); // Invalid - will throw error try { const invalid = new Point(NaN, 50); } catch (error) { console.error(error); // "Point is invalid: (NaN, 50)" } ``` -------------------------------- ### Example Usage of SignaturePad with Throttle Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/06-throttle-utility.md Demonstrates how to instantiate SignaturePad with a specific throttle value. It also illustrates the internal event handling, showing the difference between raw mousemove events and throttled _strokeUpdate calls. ```typescript const canvas = document.querySelector("canvas"); const signaturePad = new SignaturePad(canvas, { throttle: 16 // Throttle to 16ms intervals (default) }); // Internally, during mouse move: // - Raw mousemove event: many per second (maybe 100+) // - Throttled _strokeUpdate: at most 1 per 16ms (~60) // - beforeUpdateStroke/afterUpdateStroke events: at most 1 per 16ms ``` -------------------------------- ### Install Signature Pad with Yarn Source: https://github.com/szimek/signature_pad/blob/master/README.md Use Yarn to add Signature Pad to your project dependencies. This is an alternative to npm for package management. ```bash yarn add signature_pad ``` -------------------------------- ### Throttling Timeline Example Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/06-throttle-utility.md Illustrates the execution pattern of the throttle function over time. It shows how calls within the 'wait' interval are handled, with the first call executing immediately and subsequent calls being queued for execution after the interval. ```text Time: 0ms 5ms 10ms 15ms 16ms 20ms 25ms 30ms Call: ✓ ✗ ✗ ✗ ✗ ✓ ✗ ✗ ↑ ↑ Immediate After wait ms ``` -------------------------------- ### Basic Signature Pad Initialization and Usage Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/00-api-overview.md Initialize a Signature Pad instance with a canvas element and listen for stroke completion events. Demonstrates how to get signature data as a URL or point data, and how to clear the canvas. ```typescript import SignaturePad from 'signature_pad'; // Get canvas element const canvas = document.querySelector('canvas'); // Create signature pad const signaturePad = new SignaturePad(canvas); // Listen for signature completion signaturePad.addEventListener('endStroke', () => { console.log('Stroke complete'); }); // Get signature as image const imageUrl = signaturePad.toDataURL('image/png'); // Get signature as point data const pointData = signaturePad.toData(); // Clear canvas signaturePad.clear(); ``` -------------------------------- ### SignaturePad Data Workflow Example Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/02-point-classes.md Demonstrates how to listen for the 'endStroke' event to retrieve drawn signature data as PointGroup arrays containing BasicPoint objects. It also shows how to send this data to a server and restore a signature from saved data using fromData(). ```typescript signaturePad.addEventListener("endStroke", () => { // Get the drawn data const data = signaturePad.toData(); // data contains PointGroup[] with BasicPoint[] arrays console.log(data[0].points[0]); // { x, y, pressure, time } // Send to server fetch("/api/signature", { method: "POST", body: JSON.stringify(data) }); }); // Restore from server const savedData = await fetch("/api/signature").then(r => r.json()); signaturePad.fromData(savedData); // Accepts BasicPoint[] wrapped in PointGroup[] ``` -------------------------------- ### Setup Full-Screen Signature Pad Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/08-usage-patterns.md Configure Signature Pad to fill the entire viewport for a full-screen drawing experience. Ensures proper canvas resizing on orientation changes and window resizes. ```typescript function setupFullScreenSignaturePad() { const canvas = document.querySelector('canvas'); // Make canvas fill viewport canvas.style.width = '100vw'; canvas.style.height = '100vh'; function resizeCanvas() { const ratio = window.devicePixelRatio; canvas.width = window.innerWidth * ratio; canvas.height = window.innerHeight * ratio; canvas.getContext('2d').scale(ratio, ratio); signaturePad.redraw(); } window.addEventListener('resize', resizeCanvas); window.addEventListener('orientationchange', () => { setTimeout(resizeCanvas, 100); }); resizeCanvas(); const signaturePad = new SignaturePad(canvas, { minWidth: 2, maxWidth: 5, throttle: 20, minDistance: 3 }); return signaturePad; } ``` -------------------------------- ### SignaturePad Data and Redraw Methods Source: https://github.com/szimek/signature_pad/blob/master/README.md Covers methods for getting and setting signature data in a structured format, and for redrawing the canvas. ```APIDOC ## SignaturePad Data and Redraw Methods ### Description Provides methods to get the signature data as an array of point groups and to draw the signature from this data. Also includes a method to redraw the canvas. ### Methods - `toData()`: Returns the signature as an array of point groups. - `fromData(data, [options])`: Draws the signature from an array of point groups. The `clear` option (defaults to `true`) determines if the canvas is cleared before drawing. - `redraw()`: Redraws the entire canvas. Useful after manual canvas manipulations or when the canvas size changes. ### Code Example ```javascript const canvas = document.querySelector("canvas"); const signaturePad = new SignaturePad(canvas); // Get signature data const signatureData = signaturePad.toData(); // Draw signature from data (clears canvas by default) signaturePad.fromData(signatureData); // Draw signature from data without clearing signaturePad.fromData(signatureData, { clear: false }); // Redraw the canvas signaturePad.redraw(); ``` ``` -------------------------------- ### PointGroup Example: Drawing with Changing Colors Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/04-types.md Illustrates how SignaturePad handles strokes with different colors by capturing penColor per PointGroup. Redrawing preserves these distinct colors. ```typescript // Draw signature with changing colors signaturePad.penColor = "black"; // User draws first stroke... signaturePad.penColor = "red"; // User draws second stroke... const data = signaturePad.toData(); // data[0] has penColor: "black" // data[1] has penColor: "red" // Redraw preserves colors signaturePad.fromData(data); ``` -------------------------------- ### Signature Pad Dot Size Example Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/07-configuration.md Demonstrates how `dotSize` interacts with `minWidth` and `maxWidth`. When the user taps without dragging, a circle with the specified `dotSize` is drawn. When dragging, a line with width varying between `minWidth` and `maxWidth` is drawn. ```typescript const pad = new SignaturePad(canvas, { dotSize: 3, minWidth: 1, maxWidth: 5 }); ``` -------------------------------- ### Listen for Signature Pad Events Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/04-types.md Attach an event listener to the `beginStroke` event to capture details about the start of a new stroke, including coordinates (x, y) and pressure. The event data is available in `ev.detail`. ```typescript signaturePad.addEventListener('beginStroke', (ev: CustomEvent) => { const { x, y, pressure } = ev.detail; console.log(`Started at (${x}, ${y}) with pressure ${pressure}`); }); ``` -------------------------------- ### Save and Load Signature Data Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/00-api-overview.md Use `toData()` to get the signature data and `fromData()` to load it. Store the data as a JSON string in local storage. ```typescript // Save const data = signaturePad.toData(); localStorage.setItem('signature', JSON.stringify(data)); // Load const saved = localStorage.getItem('signature'); if (saved) { signaturePad.fromData(JSON.parse(saved)); } ``` -------------------------------- ### Initialization with Options Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/00-api-overview.md Explains how to configure Signature Pad with various options during initialization to customize its appearance and behavior. ```APIDOC ## Initialization with Options ### Description Customize the Signature Pad's appearance and drawing behavior by providing an options object during initialization. ### Options - `minWidth` (number): Minimum width of the line. - `maxWidth` (number): Maximum width of the line. - `penColor` (string): Color of the pen. - `backgroundColor` (string): Background color of the canvas. - `throttle` (number): Throttle time for drawing events. - `minDistance` (number): Minimum distance between points. - `dotSize` (number): Size of the dots. - `velocityFilterWeight` (number): Weight for velocity filtering. - `compositeOperation` (string): Composite operation for drawing. - `canvasContextOptions` (object): Options for the canvas context. ### Example ```typescript const signaturePad = new SignaturePad(canvas, { minWidth: 1, maxWidth: 5, penColor: 'rgb(66, 133, 244)', backgroundColor: 'rgb(255, 255, 255)', throttle: 16, minDistance: 5, dotSize: 0, velocityFilterWeight: 0.7, compositeOperation: 'source-over', canvasContextOptions: {} }); ``` ``` -------------------------------- ### Basic Usage Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/00-api-overview.md Demonstrates the fundamental steps to initialize Signature Pad, add event listeners, and clear the canvas. ```APIDOC ## Basic Usage ### Description This section shows how to create a new Signature Pad instance, listen for drawing events, and clear the canvas. ### Initialization ```typescript import SignaturePad from 'signature_pad'; // Get canvas element const canvas = document.querySelector('canvas'); // Create signature pad const signaturePad = new SignaturePad(canvas); ``` ### Event Handling ```typescript signaturePad.addEventListener('endStroke', () => { console.log('Stroke complete'); }); ``` ### Clearing the Canvas ```typescript signaturePad.clear(); ``` ``` -------------------------------- ### beginStroke Event Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/05-event-handling.md Fired when a stroke begins. This event can be canceled to prevent the stroke from starting. ```APIDOC ## Event: beginStroke Fired when a stroke begins (mouse down, touch start, pointer down). **Properties:** | Property | Type | Value | |----------|------|-------| | `type` | string | `"beginStroke"` | | `detail` | `SignatureEvent` | Event details including x, y, pressure, pressure | | `cancelable` | boolean | `true` | **Can be canceled?** Yes. Call `event.preventDefault()` to cancel the stroke. **Fires when:** 1. Mouse button pressed (left button only) 2. Single touch starts 3. Pointer device pressed (not iOS) **Does not fire when:** - Multiple touches or buttons pressed - Stroke already in progress **Example:** ```typescript let strokeCount = 0; signaturePad.addEventListener("beginStroke", (event) => { const { x, y, pressure } = event.detail; console.log(`Stroke #${++strokeCount} started at (${x}, ${y})`); // Cancel stroke if certain conditions met if (strokeCount > 10) { event.preventDefault(); console.log("Too many strokes, canceled"); } }); ``` ``` -------------------------------- ### Instantiate SignaturePad with Custom Options Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/01-signature-pad-class.md Demonstrates how to create a new SignaturePad instance, configuring properties like minimum and maximum line width, pen color, and background color for the signature canvas. ```typescript const canvas = document.querySelector("canvas"); const signaturePad = new SignaturePad(canvas, { minWidth: 1, maxWidth: 5, penColor: "rgb(66, 133, 244)", backgroundColor: "rgb(255, 255, 255)" }); ``` -------------------------------- ### Initialize SignaturePad with Options Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/07-configuration.md Instantiate SignaturePad by passing an options object to the constructor. This sets up the canvas with your desired configurations. ```typescript const signaturePad = new SignaturePad(canvas, options); ``` -------------------------------- ### Dispatch Custom Event Internally Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/05-event-handling.md Example of how SignaturePad internally dispatches custom events, such as 'beginStroke'. The `cancelable` option allows `preventDefault()` to halt further processing. ```typescript // SignaturePad dispatches custom events internally const event = new CustomEvent('beginStroke', { detail: signatureEvent, cancelable: true }); const notCanceled = this.dispatchEvent(event); if (notCanceled) { // Proceed with stroke } ``` -------------------------------- ### SignaturePad Initialization and Basic Usage Source: https://github.com/szimek/signature_pad/blob/master/README.md Demonstrates how to initialize SignaturePad on a canvas element and use basic methods like toDataURL and toSVG. ```APIDOC ## SignaturePad Initialization and Basic Usage ### Description Initializes the SignaturePad on a given canvas element and shows examples of how to convert the signature to different data formats (Data URL, SVG) and how to draw from a Data URL. ### Methods - `new SignaturePad(canvas, [options])`: Constructor to create a new SignaturePad instance. - `toDataURL(mimetype, quality)`: Returns the signature as a data URL. Supports PNG, JPEG, and SVG formats with optional quality for JPEG. - `toSVG([options])`: Returns the signature as an SVG string. Options can include `includeBackgroundColor` and `includeDataUrl`. - `fromDataURL(dataURL, [options])`: Draws a signature from a data URL. Options can specify `ratio`, `width`, `height`, `xOffset`, and `yOffset`. ### Code Example ```javascript const canvas = document.querySelector("canvas"); // Initialize with default options const signaturePad = new SignaturePad(canvas); // Save as PNG const pngDataUrl = signaturePad.toDataURL(); // Save as JPEG with quality 0.5 const jpegDataUrl = signaturePad.toDataURL("image/jpeg", 0.5); // Save as SVG const svgString = signaturePad.toSVG(); // Draw from a PNG data URL signaturePad.fromDataURL("data:image/png;base64,iVBORw0K..."); // Draw from a PNG data URL with options signaturePad.fromDataURL("data:image/png;base64,iVBORw0K...", { ratio: 1, width: 400, height: 200, xOffset: 100, yOffset: 50 }); ``` ``` -------------------------------- ### Trim Empty Space Around Signature (Server-Side) Source: https://github.com/szimek/signature_pad/blob/master/README.md Example of using ImageMagick's 'convert' command with the 'trim' option to remove whitespace from an image. ```bash convert -trim input.jpg output.jpg ``` -------------------------------- ### Listen for Stroke Beginning Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/05-event-handling.md Fires when a stroke begins. Can be canceled to prevent the stroke. Useful for tracking stroke counts or validating conditions before a stroke starts. ```typescript let strokeCount = 0; signaturePad.addEventListener("beginStroke", (event) => { const { x, y, pressure } = event.detail; console.log(`Stroke #${++strokeCount} started at (${x}, ${y})`); // Cancel stroke if certain conditions met if (strokeCount > 10) { event.preventDefault(); console.log("Too many strokes, canceled"); } }); ``` -------------------------------- ### Signature Pad Initialization with Options Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/00-api-overview.md Initialize a Signature Pad instance with custom options to control appearance and behavior, such as line width, pen color, and background color. ```typescript const signaturePad = new SignaturePad(canvas, { minWidth: 1, maxWidth: 5, penColor: 'rgb(66, 133, 244)', backgroundColor: 'rgb(255, 255, 255)', throttle: 16, minDistance: 5, dotSize: 0, velocityFilterWeight: 0.7, compositeOperation: 'source-over', canvasContextOptions: {} }); ``` -------------------------------- ### Manage Signature Data Source: https://github.com/szimek/signature_pad/blob/master/README.md Get the signature as an array of point groups or draw a signature from such an array. The `fromData` method can optionally preserve the existing drawing. ```javascript // Returns signature image as an array of point groups const data = signaturePad.toData(); ``` ```javascript // Draws signature image from an array of point groups signaturePad.fromData(data); ``` ```javascript // Draws signature image from an array of point groups, without clearing your existing image (clear defaults to true if not provided) signaturePad.fromData(data, { clear: false }); ``` -------------------------------- ### PointGroup Interface Definition Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/04-types.md Represents a collection of points forming a single stroke or dot, including associated drawing options. Captures options at stroke start. ```typescript interface PointGroup extends PointGroupOptions { points: BasicPoint[]; } ``` -------------------------------- ### Get Signature as SVG String Source: https://github.com/szimek/signature_pad/blob/master/README.md Retrieve the signature as an SVG string. Options are available to include the background color or a data URL representation within the SVG. ```javascript // Return svg string without converting to base64 signaturePad.toSVG(); // "" signaturePad.toSVG({includeBackgroundColor: true}); // add background color to svg output signaturePad.toSVG({includeDataUrl: true}); // add data url added with fromDataUrl to svg output background ``` -------------------------------- ### Get Signature as Base64 Data URL Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/08-usage-patterns.md Retrieves the signature as a base64 encoded data URL, defaulting to PNG format. This is useful for embedding the signature directly into HTML. ```typescript function getBase64Signature() { return signaturePad.toDataURL(); // PNG base64 by default } // Use for embedding in HTML function displayBase64Signature() { const dataUrl = getBase64Signature(); const img = document.createElement('img'); img.src = dataUrl; document.body.appendChild(img); } ``` -------------------------------- ### SignaturePad Constructor Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/01-signature-pad-class.md Initializes a new SignaturePad instance. It takes a canvas element and an optional options object to configure its behavior and appearance. ```APIDOC ## Constructor SignaturePad ### Description Initializes a new SignaturePad instance. ### Parameters #### Path Parameters - **canvas** (HTMLCanvasElement) - Required - The HTML canvas element to draw signatures on. Event handlers are automatically attached to this element. - **options** (Options) - Optional - Configuration options for the signature pad instance. ### Options Parameter Details #### Option - **minWidth** (number) - Optional - Minimum width of a drawn line in pixels. Default: `0.5`. - **maxWidth** (number) - Optional - Maximum width of a drawn line in pixels. Default: `2.5`. - **throttle** (number) - Optional - Milliseconds between point updates. Set to `0` to disable throttling. Prevents excessive event processing on high-frequency input. Default: `16`. - **minDistance** (number) - Optional - Minimum distance in pixels between consecutive points before a new point is recorded. Helps reduce the number of points stored. Default: `5`. - **dotSize** (number) - Optional - Radius of a single dot (drawn when the user taps without dragging). When `0`, uses the average of `minWidth` and `maxWidth`. Default: `0`. - **penColor** (string) - Optional - Color used to draw lines. Accepts any valid CSS color format (`"rgb(255,0,0)"`, `"#FF0000"`, `"rgba(255,0,0,0.5)"`, etc.). Default: `"black"`. - **backgroundColor** (string) - Optional - Color used to fill the canvas background. Use a non-transparent color like `"rgb(255,255,255)"` when saving as JPEG. Default: `"rgba(0,0,0,0)"`. - **velocityFilterWeight** (float) - Optional - Weighted average factor (0-1) applied to velocity calculations. Higher values give more weight to recent velocity. Affects stroke width variation. Default: `0.7`. - **compositeOperation** (GlobalCompositeOperation) - Optional - Canvas composite operation for drawing. See MDN for all valid values (e.g., `"multiply"`, `"screen"`, `"lighten"`). Default: `"source-over"`. - **canvasContextOptions** (CanvasRenderingContext2DSettings) - Optional - Additional options passed to `canvas.getContext('2d', options)`. Used for advanced canvas settings like color space. Default: `{}`. ### Request Example ```typescript const canvas = document.querySelector("canvas"); const signaturePad = new SignaturePad(canvas, { minWidth: 1, maxWidth: 5, penColor: "rgb(66, 133, 244)", backgroundColor: "rgb(255, 255, 255)" }); ``` ``` -------------------------------- ### Configure fromDataURL Method Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/04-types.md Customize image loading with FromDataUrlOptions. Control scaling using `ratio`, `width`, and `height`, and adjust positioning with `xOffset` and `yOffset`. ```typescript interface FromDataUrlOptions { ratio?: number; width?: number; height?: number; xOffset?: number; yOffset?: number; } ``` ```typescript const ratio = window.devicePixelRatio; const imageUrl = "data:image/png;base64,..."; // Default positioning (fill canvas) await signaturePad.fromDataURL(imageUrl); // Custom positioning await signaturePad.fromDataURL(imageUrl, { ratio: ratio, width: 400, height: 200, xOffset: 50, yOffset: 25 }); ``` -------------------------------- ### Initialize Signature Pad with Event Listeners Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/05-event-handling.md Instantiate Signature Pad and attach event listeners for drawing actions. Ensure the target element exists and is valid. ```typescript const canvas = document.querySelector("canvas"); const signaturePad = new SignaturePad(canvas); // Add event listeners for drawing signaturePad.on("beginStroke", () => { console.log("Begin stroke"); }); signaturePad.on("endStroke", () => { console.log("End stroke"); }); signaturePad.on("beforeBegin", () => { console.log("Before begin"); }); signaturePad.on("afterEnd", () => { console.log("After end"); }); ``` -------------------------------- ### Track Signature Metadata Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/05-event-handling.md Collect metadata like start time, end time, point count, and pressure during signature capture. Listen to `beginStroke`, `afterUpdateStroke`, and `endStroke` events. ```typescript let signatureMetadata = { startTime: null, endTime: null, pointCount: 0, pressure: [] }; signaturePad.addEventListener("beginStroke", (event) => { signatureMetadata.startTime = Date.now(); signatureMetadata.pointCount = 0; }); signaturePad.addEventListener("afterUpdateStroke", (event) => { signatureMetadata.pointCount++; signatureMetadata.pressure.push(event.detail.pressure); }); signaturePad.addEventListener("endStroke", (event) => { signatureMetadata.endTime = Date.now(); signatureMetadata.duration = signatureMetadata.endTime - signatureMetadata.startTime; console.log(signatureMetadata); }); ``` -------------------------------- ### Initialize Signature Pad Source: https://github.com/szimek/signature_pad/blob/master/README.md Instantiate SignaturePad with a canvas element. Options can be provided during initialization to customize its appearance and behavior. ```javascript const canvas = document.querySelector("canvas"); const signaturePad = new SignaturePad(canvas); ``` ```javascript const signaturePad = new SignaturePad(canvas, { minWidth: 5, maxWidth: 10, penColor: "rgb(66, 133, 244)" }); ``` -------------------------------- ### addEventListener() Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/01-signature-pad-class.md Registers an event listener for signature-related events. This method allows you to react to specific drawing actions like the start or end of a stroke, or updates during drawing. It inherits from `SignatureEventTarget`. ```APIDOC ## addEventListener() ### Description Registers an event listener for signature events. Inherits from `SignatureEventTarget`. ### Method ```typescript addEventListener( type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions ): void ``` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Parameters Table | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | type | `string` | Yes | Event type: `"beginStroke"`, `"endStroke"`, `"beforeUpdateStroke"`, or `"afterUpdateStroke"`. | | listener | `EventListenerOrEventListenerObject | null` | Yes | Function or object with `handleEvent` method to call when event fires. | | options | `boolean | AddEventListenerOptions` | No | Event listener options (e.g., `{ once: true }` to trigger only once). | ### Available Events | Event | Detail (CustomEvent.detail) | Cancelable | Description | |-------|---------------------------|-----------|-------------| | `beginStroke` | `SignatureEvent` | Yes | Fired before a stroke begins. Call `event.preventDefault()` to cancel the stroke. | | `endStroke` | `SignatureEvent` | No | Fired after a stroke ends. | | `beforeUpdateStroke` | `SignatureEvent` | No | Fired before a stroke is updated with a new point. | | `afterUpdateStroke` | `SignatureEvent` | No | Fired after a stroke is updated. | **SignatureEvent structure:** See [Types Documentation](./types.md). ### Example ```typescript // Listen for stroke completion signaturePad.addEventListener("endStroke", (event) => { const signatureEvent = event.detail; console.log(`Stroke ended at (${signatureEvent.x}, ${signatureEvent.y})`); }); // Cancel stroke if needed signaturePad.addEventListener("beginStroke", (event) => { if (someCondition) { event.preventDefault(); } }, { once: true }); // Listen for updates signaturePad.addEventListener("afterUpdateStroke", (event) => { // Called frequently during drawing }); ``` ``` -------------------------------- ### Signature Pad Initialization with Custom Options Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/08-usage-patterns.md Configure the Signature Pad with custom options for line width, color, background, and drawing sensitivity. These options allow for fine-tuning the signature appearance and drawing experience. ```typescript const signaturePad = new SignaturePad(canvas, { minWidth: 1, maxWidth: 5, penColor: 'rgb(66, 133, 244)', backgroundColor: 'rgb(255, 255, 255)', throttle: 16, minDistance: 5 }); ``` -------------------------------- ### Bezier Class Constructor Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/03-bezier-curves.md Defines a cubic Bézier curve with specified start and end points, control points, and stroke widths. Use this to initialize a new Bezier curve instance. ```typescript constructor( startPoint: Point, control2: BasicPoint, control1: BasicPoint, endPoint: Point, startWidth: number, endWidth: number ) ``` -------------------------------- ### Initialize SignaturePad with Options Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/04-types.md Configure SignaturePad during initialization using the Options interface. This allows customization of drawing behavior, appearance, and canvas context settings. ```typescript interface Options extends Partial { minDistance?: number; backgroundColor?: string; throttle?: number; canvasContextOptions?: CanvasRenderingContext2DSettings; } ``` ```typescript const canvas = document.querySelector("canvas"); const signaturePad = new SignaturePad(canvas, { minWidth: 2, maxWidth: 8, penColor: "rgb(66, 133, 244)", backgroundColor: "rgb(255, 255, 255)", throttle: 0, // No throttling minDistance: 3, canvasContextOptions: { willReadFrequently: true } }); ``` -------------------------------- ### SignaturePad Constructor Options Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/04-types.md Configuration options for the SignaturePad constructor. These options allow customization of drawing behavior, appearance, and canvas context settings. ```APIDOC ## Options for SignaturePad Constructor ### Description Configuration options for SignaturePad constructor. Extends PointGroupOptions (all fields optional) and adds additional options. ### Fields - `minDistance` (number) - Optional - Minimum distance in pixels before a new point is recorded. Default: `5` - `backgroundColor` (string) - Optional - Background color (transparent black by default). Use "rgb(255,255,255)" for JPEG export. Default: `"rgba(0,0,0,0)"` - `throttle` (number) - Optional - Milliseconds between point updates. Set to 0 to disable. Default: `16` - `canvasContextOptions` (CanvasRenderingContext2DSettings) - Optional - Options passed to canvas.getContext('2d', options). Default: `{}` - `dotSize` (number) - Optional - (Inherited from PointGroupOptions) Default: `0` - `minWidth` (number) - Optional - (Inherited from PointGroupOptions) Default: `0.5` - `maxWidth` (number) - Optional - (Inherited from PointGroupOptions) Default: `2.5` - `penColor` (string) - Optional - (Inherited from PointGroupOptions) Default: `"black"` - `velocityFilterWeight` (number) - Optional - (Inherited from PointGroupOptions) Default: `0.7` - `compositeOperation` (GlobalCompositeOperation) - Optional - (Inherited from PointGroupOptions) Default: `"source-over"` ### Example ```typescript const canvas = document.querySelector("canvas"); const signaturePad = new SignaturePad(canvas, { minWidth: 2, maxWidth: 8, penColor: "rgb(66, 133, 244)", backgroundColor: "rgb(255, 255, 255)", throttle: 0, // No throttling minDistance: 3, canvasContextOptions: { willReadFrequently: true } }); ``` ``` -------------------------------- ### Configure Signature Pad Canvas Context Options Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/04-types.md Instantiate SignaturePad with custom canvas context options for performance tuning, such as `willReadFrequently` and `colorSpace`. Also allows setting `throttle` and `minDistance` for drawing behavior. ```typescript // Create signature pad with high-performance settings const pad = new SignaturePad(canvas, { canvasContextOptions: { willReadFrequently: false, // Only use if you'll call getImageData colorSpace: "srgb" }, throttle: 16, minDistance: 5 }); ``` -------------------------------- ### Serialize and Deserialize Signature Data Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/04-types.md Use `toData()` to get signature points as an array of PointGroup objects, which can be sent to a server. Load signature data back into the pad using `fromData()` with the received JSON. ```typescript // Get signature data const data: PointGroup[] = signaturePad.toData(); // Send to server const response = await fetch('/api/signature', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }); // Load from server const loadedData: PointGroup[] = await response.json(); signaturePad.fromData(loadedData); ``` -------------------------------- ### Configuration Options Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/README.md Reference for all configuration options available for Signature Pad, detailing their purpose and effect. ```APIDOC ## Configuration Options Signature Pad accepts a configuration object during instantiation or can be updated at runtime. Key options include: - **`minWidth`** (number) - Minimum stroke width. - **`maxWidth`** (number) - Maximum stroke width. - **`penColor`** (string) - Color of the signature stroke. - **`backgroundColor`** (string) - Background color of the canvas. - **`throttle`** (number) - Time in milliseconds to throttle stroke updates. - **`minDistance`** (number) - Minimum distance between points to trigger an update. - **`dotSize`** (number | Function) - Size of the dot drawn for taps. - **`velocityFilterWeight`** (number) - Weight for velocity-based smoothing. - **`compositeOperation`** (string) - Canvas composite operation (e.g., `source-over`, `destination-over`). - **`canvasContextOptions`** (object) - Options passed directly to `canvas.getContext()`. Preset configurations are available for common use cases (e.g., `precise`, `natural`, `bold`, `mobile`, `eraser`). ``` -------------------------------- ### on() Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/00-api-overview.md Enables event handlers for the signature pad. ```APIDOC ## on() ### Description Enables event handlers for the signature pad. ### Method `on()` ### Parameters None ### Request Example ```typescript signaturePad.on(); ``` ### Response None (This is a method call) #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Signature Pad Initialization with Throttling Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/05-event-handling.md Configure the throttle option to control the frequency of beforeUpdateStroke and afterUpdateStroke events. The default is 16ms, suitable for desktop performance. Setting throttle to 0 fires events on every input, while higher values like 50ms are optimized for mobile. ```typescript const pad = new SignaturePad(canvas, { throttle: 16 // Default: max 1 event per 16ms (~60Hz) }); ``` ```typescript // High-frequency drawing feedback (desktop only) const pad = new SignaturePad(canvas, { throttle: 0 }); ``` ```typescript // Mobile-optimized const pad = new SignaturePad(canvas, { throttle: 30 }); ``` -------------------------------- ### SignaturePad Class Methods Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/README.md Documentation for the main SignaturePad class, including its constructor, public methods for core functionality, data manipulation, export, import, and event handling. ```APIDOC ## SignaturePad Class ### Constructor Initializes a new instance of SignaturePad. Accepts an optional configuration object. ### Public Methods #### Core - **`clear()`** - Description: Clears the signature pad, removing all drawn strokes. - Signature: `clear(): void` - **`isEmpty()`** - Description: Checks if the signature pad is empty (contains no strokes). - Signature: `isEmpty(): boolean` - **`redraw()`** - Description: Redraws the signature based on the current internal data. - Signature: `redraw(): void` #### Data Manipulation - **`toData()`** - Description: Returns the signature data in a JSON format. - Signature: `toData(): SignaturePoint[]` - **`fromData(data: SignaturePoint[])`** - Description: Loads a signature from JSON data. - Signature: `fromData(data: SignaturePoint[]): void` #### Export - **`toDataURL(type?: string, encoderOptions?: any)`** - Description: Exports the signature as a data URL (e.g., PNG, JPEG). - Signature: `toDataURL(type?: string, encoderOptions?: any): string` - **`toSVG(options?: ToSVGOptions)`** - Description: Exports the signature as an SVG string. - Signature: `toSVG(options?: ToSVGOptions): string` #### Import - **`fromDataURL(dataURL: string, options?: FromDataUrlOptions)`** - Description: Loads a signature from a data URL. - Signature: `fromDataURL(dataURL: string, options?: FromDataUrlOptions): void` #### Event Handling - **`on(event: string, listener: Function)`** - Description: Attaches an event listener to the signature pad. - Signature: `on(event: string, listener: Function): void` - **`off(event: string, listener: Function)`** - Description: Removes an event listener from the signature pad. - Signature: `off(event: string, listener: Function): void` - **`addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions)`** - Description: Adds an event listener to the signature pad. - Signature: `addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void` ### Properties - All properties are documented with their types. ``` -------------------------------- ### SignaturePad Options Source: https://github.com/szimek/signature_pad/blob/master/README.md Explains the various configuration options available for customizing the appearance and behavior of the SignaturePad. ```APIDOC ## SignaturePad Options ### Description These options allow you to customize the appearance and drawing behavior of the SignaturePad. They can be set during initialization or modified at runtime. ### Options - `dotSize` (float or function): Radius of a single dot and 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 `x` milliseconds. Set to `0` to disable 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. Accepts any color format usable by `context.fillStyle`. Defaults to `"rgba(0,0,0,0)"` (transparent black). - `penColor` (string): Color used to draw the lines. Accepts any color format usable by `context.fillStyle`. Defaults to `"black"`. - `velocityFilterWeight` (float): Weight used to modify new velocity based on the previous velocity. Defaults to `0.7`. - `canvasContextOptions` (CanvasRenderingContext2DSettings): Options passed to the `canvas.getContext('2d')` call. ### Usage #### Initialization ```javascript const signaturePad = new SignaturePad(canvas, { minWidth: 5, maxWidth: 10, penColor: "rgb(66, 133, 244)" }); ``` #### Runtime ```javascript const signaturePad = new SignaturePad(canvas); signaturePad.minWidth = 5; signaturePad.maxWidth = 10; signaturePad.penColor = "rgb(66, 133, 244)"; ``` ``` -------------------------------- ### Set Signature Pad Options Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/08-usage-patterns.md Initialize Signature Pad with custom options to control pen color, min width, and max width. These options affect the appearance of the drawn signature. ```javascript const canvas = document.querySelector("canvas"); const signaturePad = new SignaturePad(canvas, { minWidth: 1, maxWidth: 5, penColor: "rgb(0, 0, 255)" }); ``` -------------------------------- ### HTML Structure for Signature Pad Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/00-api-overview.md This HTML sets up a canvas element and buttons for controlling the signature pad. It includes the UMD bundle from a CDN and initializes the Signature Pad instance. ```html
``` -------------------------------- ### Configure Signature Pad Canvas Context Options Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/07-configuration.md Pass advanced Canvas 2D context options during initialization. This includes settings like `alpha`, `willReadFrequently`, and `colorSpace`. ```typescript new SignaturePad(canvas, { canvasContextOptions: { alpha: true, willReadFrequently: false, colorSpace: "srgb" } }); ``` -------------------------------- ### Point Data Structures Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/README.md Documentation for point-related classes and interfaces used within Signature Pad, including `BasicPoint`, `Point`, and their associated methods. ```APIDOC ## Point Data Structures ### `BasicPoint` Interface Represents a basic point with x, y coordinates, pressure, and time. - **`x`** (number) - The x-coordinate. - **`y`** (number) - The y-coordinate. - **`pressure`** (number) - The pressure applied at the point. - **`time`** (number) - The timestamp when the point was recorded. ### `Point` Class An enhanced point class with methods for calculations. #### Methods - **`distanceTo(point: Point)`** - Description: Calculates the Euclidean distance to another point. - Signature: `distanceTo(point: Point): number` - **`equals(point: Point)`** - Description: Compares this point with another point for equality. - Signature: `equals(point: Point): boolean` - **`velocityFrom(startPoint: Point)`** - Description: Calculates the speed from a starting point. - Signature: `velocityFrom(startPoint: Point): number` ``` -------------------------------- ### Performance Tuning for CPU-Constrained Devices Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/07-configuration.md Aggressively tune performance for devices with limited CPU power by increasing throttling, using sparser point recording, limiting line width variance, and applying heavy smoothing. ```typescript new SignaturePad(canvas, { throttle: 50, // Aggressive throttling minDistance: 10, // Sparse point recording minWidth: 1, maxWidth: 3, // Limit variance velocityFilterWeight: 0.9 // Smooth changes }); ``` -------------------------------- ### SignaturePad.fromDataURL() Options Source: https://github.com/szimek/signature_pad/blob/master/_autodocs/04-types.md Options for the `fromDataURL()` method, used to control the positioning, scaling, and pixel ratio of an image drawn from a data URL. ```APIDOC ## fromDataURL Options ### Description Options for the `fromDataURL()` method, controlling image positioning and scaling. ### Fields - `ratio` (number) - Optional - Pixel ratio for scaling. Use same ratio as canvas setup. Default: `window.devicePixelRatio || 1` - `width` (number) - Optional - Width in canvas pixels. Default: `canvas.width / ratio` - `height` (number) - Optional - Height in canvas pixels. Default: `canvas.height / ratio` - `xOffset` (number) - Optional - Horizontal offset in canvas pixels. Default: `0` - `yOffset` (number) - Optional - Vertical offset in canvas pixels. Default: `0` ### Example ```typescript const ratio = window.devicePixelRatio; const imageUrl = "data:image/png;base64,..."; // Default positioning (fill canvas) await signaturePad.fromDataURL(imageUrl); // Custom positioning await signaturePad.fromDataURL(imageUrl, { ratio: ratio, width: 400, height: 200, xOffset: 50, yOffset: 25 }); ``` ```