Thursday 1 May 2014

jQuery: Signature Pad



Signature Pad

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

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/thomasjbradley/signature-pad/

Demos

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.

How to Use the Plugin

First, include all the required Javascript files: jquery.jsjquery.signaturepad.jsflashcanvas.jsand 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

Accepting Signatures

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.

Javascript

$(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.

HTML 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.
Further HTML Explanation
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.

Form Submission & Validation

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.

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

Regenerating Signatures

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.

Javascript

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 displayOnlyproperty 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.
Alternative Javascript
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.

HTML Template

<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.

Resizing the Signature Pad

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

Converting to an Image

Client Side

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.

Server Side

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.

Saving to a Database

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:

$sig = $_POST['output'];

// or the better way, using PHP filters
$sig = filter_input(INPUT_POST, 'output', FILTER_UNSAFE_RAW);

PHP & MySQL Tutorial


Options

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

Changing Default 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;