A jQuery plugin for assisting in the creation of an HTML5 canvas based signature pad. Records the drawn signature in JSON for later regeneration.
- Introduction
- Demos
- Using the Plugin
- Converting to an Image
- Saving to a Database
- Options
- API
- Compressing the Output
- Version History
- License
The Signature Pad jQuery plugin will transform an HTML form into a signature pad. The Signature Pad has two modes: TypeIt and DrawIt. In TypeIt mode the user’s signature is automatically generated as HTML text, styled with @font-face
, from the input field where they type their name. In DrawIt mode the user is able to draw their signature on the canvas element.
The drawn signature is written out to a hidden input field as a JSON array using JSON.stringify()
. Since the signature is saved as JSON it can be submitted as part of the form and kept on file. Using the JSON array, the signature can then be regenerated into the canvas element for display.
Obviously, Signature Pad has a couple extra dependencies: Douglas Crockford’s json2.js and FlashCanvas 1.5. (Both scripts are included in the downloadable package.)
Signature Pad tries to maintain a certain level of progressive enhancement, while still giving developers enough control. There is very little generated HTML. The HTML in the examples has some elements that should be hidden by default (including canvas). Signature Pad will trigger the display of certain items if the browser supports Javascript and canvas.
Signature Pad works with both mouse and touch devices.
Get the source code on GitHub: https://github.com/thread-pond/signature-pad/
Demo of accepting a signature—this demo showcases an HTML form and the Signature Pad ready to accept a new signature.
Demo of requiring a drawn signature—this demo showcases an HTML form where the user is required to draw their signature before submission.
Demo of regenerating a signature—this demo showcases regeneration of a signature from a stored JSON array.
First, include all the required Javascript files: jquery.js
, jquery.signaturepad.js
, flashcanvas.js
and json2.js
.
<!--[if lt IE 9]><script src="flashcanvas.js"></script><![endif]-->
<script src="jquery.min.js"></script>
<script src="jquery.signaturepad.min.js"></script>
<script src="json2.min.js"></script>
Don’t forget to include the flashcanvas.swf file.
And the CSS file: jquery.signaturepad.css
.
<link rel="stylesheet" href="jquery.signaturepad.css">
The CSS file contains a generic display for the form and Signature Pad, which you are encouraged to change for your web site’s theme.
After including all the external resources, simply call the jQuery plugin method on the HTML form element:
$('.sigPad').signaturePad(options);
The method accepts an options object for the Signature Pad instance. Signature Pad Options Reference
Calling the signaturePad()
method also returns an API for the Signature Pad instance. Signature Pad API Reference
When accepting a signature, it is best to wrap the Signature Pad in a form so the signature can be submitted to the server for storage.
$(document).ready(function () {
$('.sigPad').signaturePad();
});
That’s really all there is to it! (.sigPad
is the class for the form element itself.) Of course there is some corresponding HTML, have a look below for the template.
<form method="post" action="" class="sigPad">
<label for="name">Print your name</label>
<input type="text" name="name" id="name" class="name">
<p class="typeItDesc">Review your signature</p>
<p class="drawItDesc">Draw your signature</p>
<ul class="sigNav">
<li class="typeIt"><a href="#type-it" class="current">Type It</a></li>
<li class="drawIt"><a href="#draw-it">Draw It</a></li>
<li class="clearButton"><a href="#clear">Clear</a></li>
</ul>
<div class="sig sigWrapper">
<div class="typed"></div>
<canvas class="pad" width="198" height="55"></canvas>
<input type="hidden" name="output" class="output">
</div>
<button type="submit">I accept the terms of this agreement.</button>
</form>
This is the HTML used on the accept demo and contains all the bits that Signature Pad looks for. Remember, all of the class names are configurable options.
Let’s go through it and explain in detail some of the important parts.
<input type="text" name="name" id="name" class="name">
The value of the .name
input element is used for creating the automatically generated signature.
<p class="typeItDesc">Review your signature</p>
<p class="drawItDesc">Draw your signature</p>
These two paragraphs, .typeItDesc
and .drawItDesc
are used as descriptive labels for the canvas Signature Pad. They are hidden or shown depending on whether the user is drawing their signature or using the automatically generated one.
<ul class="sigNav">
The .sigNav
ul element is shown if the canvas can be drawn on (aka, canvas.getContext()
is available). The list contains the links for switching modes.
<li class="clearButton"><a href="#clear">Clear</a></li>
The .clearButton
element is a button/link to allow the user to clear their signature if they mess it up. Displayed only when in DrawIt mode.
<div class="sig sigWrapper">
The .sig
and .sigWrapper
div is hidden by default and wraps the canvas and generated signature together allowing overlapping positions.
<div class="typed"></div>
The .typed
div will have the value typed into the input field inserted into it. This is effectively the automatically generated signature. It can be styled in any fashion, but the samples use @font-face
to make the text look semi-handwritten.
<canvas class="pad" width="198" height="55"></canvas>
Obviously, the canvas element for allowing the user to draw their signature.
<input type="hidden" name="output" class="output">
The .output
hidden input field is where the JSON representation of the signature is stored for submission to a server.
Signature Pad automatically validates the name input field on form submission by checking to see if it is empty. If the field is empty the form isn’t submitted and Signature Pad prepends an error message to the top of the form. Signature Pad assigns an error class to the input and the label and also sets the focus on the name field.
Both the error message and error class are options that can be changed. There are also options for changing the functionality of the validation.
Demo of requiring a drawn signature
The form can be set up to require the user to draw their signature as well as type their name into the field.
This example is almost identical to the above example, but since the user must draw their signature the HTML for typing their signature is not required. So remove the following two lines:
<p class="typeItDesc">Review your signature</p>
and delete:
<li class="typeIt"><a href="#type-it" class="current">Type It</a></li>
Then add the drawOnly
option to the Javascript and set it to true. This option disables the typeIt actions and validates that the user has drawn their signature.
$(document).ready(function () {
$('.sigPad').signaturePad({drawOnly:true});
});
Demo of regenerating a signature
Regenerating signatures from a JSON representation is quite simple. Signature Pad accepts the JSON (string or native Javascript array) and simply redraws the signature onto the canvas element.
var sig = [{lx:20,ly:34,mx:20,my:34},{lx:21,ly:33,mx:20,my:34},…];
$(document).ready(function () {
$('.sigPad').signaturePad({displayOnly:true}).regenerate(sig);
});
sig
is a variable that contains the JSON representation of the signature. In the above example you can see what the JSON looks like—though it has been trimmed for brevity’s sake.
Also notice that an options variable is passed into the signaturePad()
method. The displayOnly
property tells Signature Pad not to initialize any of the standard HTML elements, mouse events or click events. Signature Pad Options Reference
After initializing the canvas, call the regnerate()
method and pass it our JSON signature. This method simply redraws the signature onto the canvas element.
var api = $('.sigPad').signaturePad({displayOnly:true});
api.regenerate(sig);
Both snippets do exactly the same thing. The only difference is that in this example the API is stored in a variable and referred to later on.
<div class="sigPad signed">
<div class="sigWrapper">
<div class="typed">Sir John A. Macdonald</div>
<canvas class="pad" width="200" height="55"></canvas>
</div>
<p>Sir John A. Macdonald<br>July 1, 1867</p>
</div>
The HTML for displaying a signature is much simpler. The primary component is, of course, the canvas element. The typed <div>
is still there, for progressive enhancement, and will show the automatically generated signature using HTML and CSS if Javascript and canvas are not available.
There are a couple different places you have to update to change the size: the HTML and the CSS.
Change the dimensions of the <canvas>
tag in the HTML.
<form method="post" action="" class="sigPad">
⋮
<canvas class="pad" width="198" height="55"></canvas>
⋮
</form>
If you are using the sample CSS, there are a couple places to change widths and heights.
.sigPad {
margin: 0;
padding: 0;
width: 200px; /* Change the width */
}
.sigWrapper {
clear: both;
height: 55px; /* Change the height */
border: 1px solid #ccc;
}
The API includes a method called getSignatureImage()
which will return a Base64 encoded PNG to Javascript.
Unfortunately, the function doesn’t work in all browsers, only because the underlying toDataURL()
method of <canvas>
isn’t implemented well. The primary culprit of poor implementation is Android OS < 3. The function does work in IE thanks to FlashCanvas.
PHP to JPEG, PNG or GIF: Signature to Image is a simple PHP script that will take the JSON output and convert it to an image server-side. Read more about Signature to Image.
PHP to SVG : sigToSvg by Charles Gebhard is a script for converting the signature JSON to SVG using PHP. Check out the amazing sigToSvg on GitHub.
Python : python-signpad2image by Alan Viars is a script for converting the signature JSON to PNG using Python. Check out the fantastico python-signpad2image on GitHub.
Ruby on Rails : ruby-signaturepad-to-image.rb by Phil Hofmann is a chunk of code for converting signature JSON to PNG within a Ruby on Rails app. Check out the wam-bham ruby-signaturepad-to-image.rb on Github.
C# : SignatureToDotNet by Curtis Herbert is a script for converting the signature JSON to an image using C#. Check out the awesome SignatureToDotNet project on GitHub.
Perl : signature-to-image.pl by Jim Turner is a script for converting the signature JSON to a PNG using Perl. Check out the fabulous signature-to-image.pl on CPAN.
ColdFusion : sigJsonToImage by James Moberg is a script for converting the signature JSON to an PNG using ColdFusion. Check out the super-duper sigJsonToImage project on CFLib.org.
Java : SignatureToImageJava by Vinod Kiran is a script for converting the signature JSON to an image using Java. Check out the rad SignatureToImageJava project on GitHub.
Signature Pad outputs the signature to a hidden field named output
, which can be captured like any other form post field.
<input type="hidden" name="output" class="output">
In PHP, as an example, you can get the signature using:
<?php
$sig = $_POST['output'];
// or the better way, using PHP filters
$sig = filter_input(INPUT_POST, 'output', FILTER_UNSAFE_RAW);
Check out the sample app and tutorial on saving the signature in PHP and MySQL.
Options can be passed into the method when Signature Pad is instantiated. Only options that are different from the defaults need to be included in the options variable.
var options = {
bgColour : '#000'
, drawOnly : true
};
$('.sigPad').signaturePad(options);
The default options can be changed globally for all instances of Signature Pad on the page using the jQuery plugin construct:
$.fn.signaturePad.bgColour = '#000';
Setting default options always follows this pattern:
$.fn.signaturePad.OPTION = VALUE;
Name | Type | Default Value | Description |
---|---|---|---|
defaultAction |
string typeIt or drawIt |
typeIt |
Which action to be active on start-up. TypeIt will display the typed signature immediately; DrawIt will allow the user to draw immediately. |
displayOnly |
boolean |
false |
Initialize the canvas for signature display only; |
drawOnly |
boolean |
false |
Initialize the signature pad without the typeIt abilities; Require the user to draw a signature |
canvas |
string Representing a jQuery selector |
canvas |
Selector for the canvas element from inside the form element |
sig |
string Representing a jQuery selector |
.sig |
Parts of the signature form that require Javascript (hidden by default) |
sigNav |
string Representing a jQuery selector |
.sigNav |
The TypeIt/DrawIt navigation (hidden by default) |
bgColour |
string Representing a CSS colour |
#fff |
The colour fill for the background of the canvas Transparency: |
penColour |
string Representing a CSS colour |
#145394 |
Colour of the drawing ink |
penWidth |
integer |
2 |
Thickness, in pixels, of the drawing pen |
penCap |
string butt, round, square |
round |
Determines how the end points of each line are drawn |
lineColour |
string Representing a CSS colour |
#ccc |
Colour of the signature line |
lineWidth |
integer |
2 |
Thickness, in pixels, of the signature line |
lineMargin |
integer |
2 |
The margin on the left and the right of signature line |
lineTop |
integer |
35 |
Distance to draw the signature line from the top of the canvas |
name |
string Representing a jQuery selector |
.name |
The input field for typing a name |
typed |
string Representing a jQuery selector |
.typed |
The HTML element to display the printed name |
clear |
string Representing a jQuery selector |
.clearButton |
The button/link for clearing the canvas |
typeIt |
string Representing a jQuery selector |
.typeIt a |
The button/tab to trigger the TypeIt state for automatic signature generation (default state) |
drawIt |
string Representing a jQuery selector |
.drawIt a |
The button/tab to trigger the DrawIt state for drawing a signature on the canvas |
typeItDesc |
string Representing a jQuery selector |
.typeItDesc |
The description for TypeIt state |
drawItDesc |
string Representing a jQuery selector |
.drawItDesc |
The description for DrawIt state (hidden by default) |
output |
string Representing a jQuery selector |
.output |
The hidden input field for remembering the signature’s JSON array |
currentClass |
string Representing a valid CSS class name |
current |
The class used to mark items as being currently active. Used for the TypeIt/DrawIt tabs and the canvas wrapper element |
validateFields |
boolean |
true |
Whether the name and signature pad fields should be validated for completeness |
errorClass |
string Representing a valid CSS class name |
error |
The class applied to the new error HTML element, name input field and name input label |
errorMessage |
string |
Please enter your name |
The error message displayed on invalid submission |
errorMessageDraw |
string |
Please sign the document |
The error message displayed when in |
onBeforeValidate |
function (context, settings) |
(built in) |
Pass a function callback to be executed before the form is validated. Can be used to clear the old validation errors. Arguments
|
onFormError |
function (errors, context, settings) |
(built in) |
Pass a function callback to be executed when the form is invalid. Can be used to display error messages to the user. Arguments
|
onDraw |
function |
null |
Pass a function callback to be executed every time the user draws a new segment in their signature. |
onDrawEnd |
function |
null |
Pass a function callback to be executed whenever the user completes their drawing segment. |
The API is returned from the instantiation of the Signature Pad and can be stored in a variable or chained.
$('.sigPad').signaturePad({displayOnly:true}).regenerate(sig);
API chaining after instantiation.
var api = $('.sigPad').signaturePad({displayOnly:true});
api.regenerate(sig);
Storage of the API in a variable.
You can also get the API at a later time by recalling the signaturePad()
method.
It’s is less performant to do it this way, and much better to store the API in the initial call so you don’t have to touch the DOM again.
$('.sigPad').signaturePad({bgColour:'transparent'});
// More code or in another function
var api = $('.sigPad').signaturePad();
var sig = api.getSignature();
Later retrieval of the Signature Pad API.
Method | Arguments | Return | Description |
---|---|---|---|
signaturePad() |
string |
Retrieves the current version of Signature Pad programmatically. |
|
regenerate(paths) |
paths:array|string An array of objects representing the movement and lines of the signature |
void |
Redraws a signature on the canvas element using an array of objects representing the movement and lines of the signature |
clearCanvas() |
void |
Clears all the drawn elements off the canvas and redraws the background colour and signature line |
|
getSignature() |
array The signature as a native Javascript array |
Returns the drawn signature as a native Javascript array Each item in the array is an object following this format:
|
|
getSignatureString() |
string The signature as a JSON string; for saving |
Returns the drawn signature as a Javascript string in the JSON format The string follows this format:
|
|
getSignatureImage() |
string The Base64 encoded PNG of the signature |
Returns a Base64 encoded PNG of the canvas |
|
updateOptions(options) |
options:object An object representing the options to change |
void |
Allows for some options to be updated later in code. Only need to pass the options that are different from initialization. |
validateForm() |
boolean Whether the form is valid or not |
Allows you to call the form validation function whenever it’s best for you. As an example, in your own form validation code. Probably best to use with the validate fields option set to false: |
Signature Pad is able to create multiple instances on a single page by selecting multiple items with jQuery. The limitation lies in the API return; Signature Pad will only return the API for the last selected element.
For multiple instances it’s best to initialize each individually and store the API in a variable. But you can get the API later by re-executing the signaturePad()
method on the element.
Sometimes the JSON string output gets very large. Thankfully Jake Moening wrote a fantastic compression algorithm.
Check out Jake’s output compression algorithm Gist
Check out the changelog on GitHub.
Signature Pad is licensed under the New BSD license, which is included in the downloadable package.
All dependencies: jQuery, json2.js, and FlashCanvas retain their own licenses.