包详细信息

signature_pad

szimek3.4mMIT5.0.10

Library for drawing smooth signatures.

自述文件

Signature Pad npm tests Code Climate

Signature Pad is a JavaScript library for drawing smooth signatures. It's HTML5 canvas based and uses variable width Bézier curve interpolation based on Smoother Signatures post by Square. It works in all modern desktop and mobile browsers and doesn't depend on any external libraries.

Example

Demo

Demo works in desktop and mobile browsers. You can check out its source code for some tips on how to handle window resize and high DPI screens. You can also find more about the latter in HTML5 Rocks tutorial.

Other demos

Installation

You can install the latest release using npm:

npm install --save signature_pad

or Yarn:

yarn add signature_pad

You can also add it directly to your page using <script> tag:

<script src="https://cdn.jsdelivr.net/npm/signature_pad@4.1.7/dist/signature_pad.umd.min.js"></script>

You can select a different version at https://www.jsdelivr.com/package/npm/signature_pad.

This library is provided as UMD (Universal Module Definition) and ES6 module.

Usage

API

const canvas = document.querySelector("canvas");

const signaturePad = new SignaturePad(canvas);

// Returns signature image as data URL (see https://mdn.io/todataurl for the list of possible parameters)
signaturePad.toDataURL(); // save image as PNG
signaturePad.toDataURL("image/jpeg"); // save image as JPEG
signaturePad.toDataURL("image/jpeg", 0.5); // save image as JPEG with 0.5 image quality
signaturePad.toDataURL("image/svg+xml"); // save image as SVG data url

// Return svg string without converting to base64
signaturePad.toSVG(); // "<svg...</svg>"
signaturePad.toSVG({includeBackgroundColor: true}); // add background color to svg output

// Draws signature image from data URL (mostly uses https://mdn.io/drawImage under-the-hood)
// NOTE: This method does not populate internal data structure that represents drawn signature. Thus, after using #fromDataURL, #toData won't work properly.
signaturePad.fromDataURL("data:image/png;base64,iVBORw0K...");

// Draws signature image from data URL and alters it with the given options
signaturePad.fromDataURL("data:image/png;base64,iVBORw0K...", { ratio: 1, width: 400, height: 200, xOffset: 100, yOffset: 50 });

// Returns signature image as an array of point groups
const data = signaturePad.toData();

// Draws signature image from an array of point groups
signaturePad.fromData(data);

// 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 });

// Clears the canvas
signaturePad.clear();

// Returns true if canvas is empty, otherwise returns false
signaturePad.isEmpty();

// Unbinds all event handlers
signaturePad.off();

// Rebinds all event handlers
signaturePad.on();

Options

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. Can be any color format accepted by context.fillStyle. Defaults to "rgba(0,0,0,0)" (transparent black). Use a non-transparent color e.g. "rgb(255,255,255)" (opaque white) if you'd like to save signatures as JPEG images.
penColor
(string) Color used to draw the lines. Can be any color format accepted 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) part of the Canvas API, provides the 2D rendering context for the drawing surface of a canvas element. It is used for drawing shapes, text, images, and other objects (MDN).

You can set options during initialization:

const signaturePad = new SignaturePad(canvas, {
    minWidth: 5,
    maxWidth: 10,
    penColor: "rgb(66, 133, 244)"
});

or during runtime:

const signaturePad = new SignaturePad(canvas);
signaturePad.minWidth = 5;
signaturePad.maxWidth = 10;
signaturePad.penColor = "rgb(66, 133, 244)";

Events

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.

You can add listeners to events with .addEventListener:

const signaturePad = new SignaturePad(canvas);
signaturePad.addEventListener("beginStroke", () => {
  console.log("Signature started");
}, { once: true });

Tips and tricks

Handling high DPI screens

To correctly handle canvas on low and high DPI screens one has to take devicePixelRatio into account and scale the canvas accordingly. This scaling is also necessary to properly display signatures loaded via SignaturePad#fromDataURL. Here's an example how it can be done:

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();

Instead of resize event you can listen to screen orientation change, if you're using this library only on mobile devices. You can also throttle the resize event - you can find some examples on this MDN page.

Handling canvas resize

When you modify width or height of a canvas, it will be automatically cleared by the browser. SignaturePad doesn't know about it by itself, so you can call signaturePad.fromData(signaturePad.toData()) to reset the drawing, or signaturePad.clear() to make sure that signaturePad.isEmpty() returns correct value in this case.

This clearing of the canvas by the browser can be annoying, especially on mobile devices e.g. when screen orientation is changed. There are a few workarounds though, e.g. you can lock screen orientation, or read an image from the canvas before resizing it and write the image back after.

Handling data URI encoded images on the server side

If you are not familiar with data URI scheme, you can read more about it on Wikipedia.

There are 2 ways you can handle data URI encoded images.

You could simply store it in your database as a string and display it in HTML like this:

<img src="data:image/png;base64,iVBORw0K..." />

but this way has many disadvantages - it's not easy to get image dimensions, you can't manipulate it e.g. to create a thumbnail and it also has some performance issues on mobile devices.

Thus, more common way is to decode it and store as a file. Here's an example in Ruby:

require "base64"

data_uri = "data:image/png;base64,iVBORw0K..."
encoded_image = data_uri.split(",")[1]
decoded_image = Base64.decode64(encoded_image)
File.open("signature.png", "wb") { |f| f.write(decoded_image) }

Here's an example in PHP:

$data_uri = "data:image/png;base64,iVBORw0K...";
$encoded_image = explode(",", $data_uri)[1];
$decoded_image = base64_decode($encoded_image);
file_put_contents("signature.png", $decoded_image);

Here's an example in C# for ASP.NET:

var dataUri = "data:image/png;base64,iVBORw0K...";
var encodedImage = dataUri.Split(',')[1];
var decodedImage = Convert.FromBase64String(encodedImage);
System.IO.File.WriteAllBytes("signature.png", decodedImage);

Removing empty space around a signature

If you'd like to remove (trim) empty space around a signature, you can do it on the server side or the client side. On the server side you can use e.g. ImageMagic and its trim option: convert -trim input.jpg output.jpg. If you don't have access to the server, or just want to trim the image before submitting it to the server, you can do it on the client side as well. There are a few examples how to do it, e.g. here or here and there's also a tiny library trim-canvas that provides this functionality.

Drawing over an image

Demo: https://jsfiddle.net/szimek/d6a78gwq/

License

Released under the MIT License.

更新日志

5.0.10 (2025-06-20)

Bug Fixes

5.0.9 (2025-06-05)

Bug Fixes

5.0.8 (2025-06-05)

Bug Fixes

  • explicitly set passive: false on listeners (#829) (d28a170)

5.0.7 (2025-03-19)

Bug Fixes

5.0.6 (2025-03-14)

Bug Fixes

  • add "types" to "exports" in package.json (#817) (5623be7)

5.0.5 (2025-03-14)

Bug Fixes

  • Add conditional exports to package.json (#815) (005a090)

5.0.4 (2024-10-17)

Bug Fixes

5.0.3 (2024-08-23)

Bug Fixes

5.0.2 (2024-06-10)

Bug Fixes

  • cast type instead of global namespace (#773) (caf901b)

5.0.1 (2024-05-18)

Bug Fixes

  • Use fallback values when options object contains explicit undefined values (#772) (fe11e16)

5.0.0 (2024-05-03)

Bug Fixes

  • allow drawing outside canvas for a smoother signature (#765) (29a8b5a)
  • update deps (1955364)

BREAKING CHANGES

    • Drawing outside of the canvas will record data outside the canvas
  • Update SignatureEvent to store the original event, x, y, pressure
  • move and up events are attached once down is triggered and they are on the window/ownerDocument target

5.0.0-beta.1 (2024-04-05)

Bug Fixes

  • allow drawing outside canvas for a smoother signature (#765) (29a8b5a)

BREAKING CHANGES

  • Drawing outside of the canvas will record data outside the canvas
  • Update SignatureEvent to store the original event, x, y, pressure
  • move and up events are attached once down is triggered and they are on the window/ownerDocument target

v4:

sig1

v5

sig2

4.2.0 (2024-03-10)

Features

  • add canvasContextOptions API for use by the getContext (#761) (7abdd48)

4.1.7 (2023-11-16)

Bug Fixes

4.1.6 (2023-07-17)

Bug Fixes

4.1.5 (2023-02-22)

Bug Fixes

4.1.4 (2022-11-08)

Bug Fixes

4.1.3 (2022-11-01)

Bug Fixes

  • fix version in built files (2e0ec92)

4.1.2 (2022-11-01)

Bug Fixes

4.1.1 (2022-10-31)

Bug Fixes

4.1.0 (2022-10-30)

Features

4.0.10 (2022-10-12)

Bug Fixes

4.0.9 (2022-09-24)

Bug Fixes

  • add velocityFilterWeight to point group options (ed6c139)
  • use point group options in calculations (7495eae)

4.0.8 (2022-09-13)

Bug Fixes

4.0.7 (2022-07-21)

Bug Fixes

  • use canvas.ownerDocument in mouse events in case it is different from window.document (#637) (636a503)

4.0.6 (2022-07-18)

Bug Fixes

  • check for event.cancelable in touch events (#634) (21ab3c7)

4.0.5 (2022-06-06)

Bug Fixes

4.0.4 (2022-04-03)

Bug Fixes

4.0.3 (2022-03-18)

Bug Fixes

  • emit endStroke on pointerup outside of canvas (#604) (29b80dd)

4.0.2 (2022-01-21)

Bug Fixes

4.0.1 (2022-01-08)

Bug Fixes

  • fix iOS <= 13 (#581)

4.0.0

Bug fixes

  • Added Anonymous to crossOrigin prop (#542)
  • Set SVG viewBox size from canvas width and height (#411)
  • Save line Properties in point group (#571)
  • Don't throw error when Coordinates are strings (#573)
  • Update Dependencies

Features

  • Allow offsets when loading image via fromDataURL (#538)
  • Add clear option to fromData (#570)
  • Capture pressure when signing (#566)

Breaking changes

  • dotSize only accepts a number now and no longer accepts a function (#571)
  • SignaturePad is an event emitter. (#567) onBegin and onEnd options have been moved to events.

    The following events were added:

    • beginStroke
    • endStroke
    • beforeUpdateStroke
    • afterUpdateStroke

3.0.0-beta.4

Bug fixes

  • Fix race condition / edge case in _strokeUpdate. (ndbroadbent; fixes #480)

    Breaking changes

  • Remove CommonJS build
  • Updated development dependencies (TS 4.x; tslint -> eslint)

3.0.0-beta.3

Features

  • Add initial support for pointer events

3.0.0-beta.2

Bug fixes

  • Fix error in touchend event handler.
  • Make both params in #toDataURL optional to match Canvas#toDataURL.

Features

  • Add optional callback param to #fromDataURL.
  • Add basic unit tests for SignaturePad class.

3.0.0-beta.1

Breaking changes

  • Rewrite library using TypeScript. TypeScript declaration files are now provided by the library. Hopefully, it should be a bit easier to refactor now...
  • Rename generated build files. The new files are:
    dist/signature_pad.js         # unminified CommonJS
    dist/signature_pad.min.js     # minified CommonJS
    dist/signature_pad.umd.js     # unminified UMD
    dist/signature_pad.umd.min.js # minified UMD
    dist/signature_pad.m.js       # unminified ES module
    dist/signature_pad.m.min.js   # minified ES module
    
  • Change structure of data returned from SignaturePad#toData method. Each point group now has 2 fields: color and points. Individual points no longer have color field.

Bug Fixes

Features

  • Add very basic unit tests for Point and Bezier classes.

2.3.2

Bug Fixes

  • Fix fromData to properly handle color changes. (szimek closes #302).

2.3.1

Bug Fixes

  • Fix minDistance not being correctly initialized when set to zero. (remomueller closes #299).

2.3.0

Bug Fixes

  • Updated demo to call SignaturePad#clear on window resize, to make sure that SignaturePad#isEmpty returns the correct value. Closes #94.

Features

  • Added minDistance option to skip points that are too close to each other (in px). It improves drawing quality (especially when drawing slowly), but introduces small lag. The default value is set to 5. To switch back to the old behavior, set it to 0.

2.2.1

Bug Fixes

  • Fix #toData/#fromData to draw the last point in each curve as well. Fixes #270.
  • Fix #fromData to properly set internal data structure. Fixes #271.

2.2.0

Bug Fixes

Features

  • Allow custom ratio/width/height when loading data URL onto canvas. (halo in #253)

2.1.1

  • Fixed a bug where default value was applied for throttle when throttle was set to 0. (mkrause in #247)

2.1.0

  • No changes since 2.1.0-beta.1.

2.1.0-beta.1

2.0.0

Unfortunately, some breaking changes were introduced in 1.6.0, so to follow the semantic versioning, it's re-released as 2.0.0.

  • Removed support for Bower. If you still need it, use 1.5.3 release.
  • Moved signature_pad.js and signature_pad.min.js files to dist folder.
  • Added ES6 version of the library for use with webpack etc.

1.6.0 (deprecated in favor of 2.0.0)

  • Added support for returning signature as SVG using #fromDataURL('image/svg+xml'). jackspirou mymattcarroll szimek
  • Added #toData method that returns data points.
  • Added #fromData method that draws signature from data points.
  • Moved signature_pad.js and signature_pad.min.js files to dist folder.

1.5.3

  • Fix touchend event on touch devices. (#150) mtomic
  • Fix handling touch events in Egde browser. (#134) dideldum73

1.5.2

  • Prevent loading an empty string in fromDataURL. (#108) Remo
  • Reject points generated by resting hand (better handling of multi touch). (#48 and #57) jurreantonisse

1.5.1

  • Prevent duplicate events on tap in iOS Safari. PerfectPixel

1.5.0

  • Add on method that rebinds all event handlers. Alplob

1.4.0

  • Add off method that unbinds all event handlers. Rob-ot

1.3.6

  • Fix support for Browserify. chevett

1.3.5

  • Add support for CommonJS/AMD/UMD.

1.3.4

  • Really fix fromDataURL on HiDPI screens.

1.3.3

  • Fix fromDataURL on HiDPI screens.

1.3.2

  • Fix onBegin and onEnd callbacks when passed as options to constructor. yinsee

1.3.1

  • Fix handling touch events on mobile IE. tocsoft

1.3.0

  • Add onBegin and onEnd callbacks. rogerz

1.2.4

  • Fix bug where stroke becomes very thin. mvirkkunen

1.2.3

  • Fix SignaturePad#fromDataURL on Firefox. Fr3nzzy

1.2.2

  • Make SignaturePad#isEmpty return false after loading an image using SignaturePad#fromDataURL. krisivanov

1.2.1

  • Fixed SignaturePad#clear().

1.2.0

  • Add backgroundColor option to set custom color of the background on SignaturePad#clear().
  • Rename color option to penColor.
  • Fix passing arguments to canvas element on SignaturePad#toDataURL().