signature_pad README

The project's README from github.com/szimek/signature_pad. As one markdown file: README.md.

Signature Pad npm tests

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:

[!NOTE] Replace [version] with the version you want to use.

<script src="https://cdn.jsdelivr.net/npm/signature_pad@[version]/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
signaturePad.toSVG({includeDataUrl: true}); // add data url added with fromDataUrl to svg output background

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

// Redraw the canvas
signaturePad.redraw();

// 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.redraw() 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.

signature_pad (szimek/signature_pad)

Searching Database…

这是做什么的?一个在浏览器里绘制平滑签名的 JavaScript 库,基于 HTML5 canvas,采用 Square 博客文章 Smoother Signatures 中的变宽度贝塞尔曲线插值。
怎么把它加到页面上?在页面上放一个 canvas,然后在上面实例化签名板:new SignaturePad(canvas, { minWidth: 5, maxWidth: 10, penColor: 'rgb(66, 133, 244)' })。选项之后也能设置,比如 pad.minWidth = 5。
需要搭配 jQuery 或其他库一起用吗?不需要——它没有任何外部依赖,可以直接在所有现代桌面和移动浏览器里运行。
在缩放窗口或高分辨率屏幕上有什么坑吗?有——canvas 的尺寸必须自己调整,按 devicePixelRatio 进行缩放,然后再清空签名板,否则 isEmpty() 可能返回错误的值;示例源码里有一个可用的 resizeCanvas()。
签名可以保存成什么格式?可以用 toSVG() 导出为 SVG(选项里可以包含背景色),或者导出为 PNG data URL——README 里给出了用 Ruby、PHP 和 C# 把 data:image/png;base64 URI 解码成 signature.png 的代码片段。还可以用 toData() 序列化笔画数据,之后用 fromData() 恢复。
有撤销或擦除功能吗?README 链接了一个擦除功能的演示,clear() 可以清空整个签名板;之前保存的笔画数据可以用 fromData() 重新绘制。README 里没有记录内置的单笔撤销 API。
用户能在一张已有的图片上签名吗?可以——有一个专门在图片上绘制的演示,fromDataURL() 能把签名图片(比如 base64 的 PNG)画回签名板,并且支持 width、height 和 offset 选项。注意:调用 fromDataURL 之后内部点数据不会被填充,所以对它调用 toData() 不会起作用。
怎么裁掉签名周围的空白?在服务器端处理,比如用 ImageMagick 的 convert -trim input.jpg output.jpg;没有服务器权限的话,就在提交前在客户端裁剪——README 里指向了一些示例和一个小巧的 trim-canvas 库。
能挂钩绘制过程吗,比如检测一笔什么时候开始?可以——可以用 addEventListener 绑定监听器:'beginStroke' 事件在签名开始时触发,也支持 { once: true } 这类选项。off() 和 on() 分别用来解绑和重新绑定所有处理函数。
Creator
szimek
Size
7.1 MB
Stars
12.1K
Age
13y
Commits · 90 Days