A jQuery UIplugin
that captures or draws a signature.
It requires the jQuery UI widget and mouse modules and needs the
excanvas.js add-in for older IE versions.
The current version is 1.2.1 and is available
under the MIT licence.
For more detail see the documentation reference page.
Or see a minimal page that you could
use as a basis for your own investigations.
The signature functionality can easily be added to a div
with appropriate default settings.
You can also remove the signature functionality if it is no longer required,
or disable or enable the field to receive input.
Using metadata for configuration may require adding the jquery.metadata.js plugin to your page.
Events
You can be notified when the signature has changed via the change setting.
And you can erase the signature with the clear command and
test for any content via the isEmpty command.
Extract the signature as a JSON value, and later re-draw it from that value.
Alternately you can generate the signature as SVG, or as a data URL in PNG or JPEG format.
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;
public class SigGen {
private static final String IMAGE_FORMAT = "png";
private static final int SIGNATURE_HEIGHT = 200;
private static final int SIGNATURE_WIDTH = 400;
/**
* A point along a line within a signature.
*/
private static class Point {
private int x;
private int y;
public Point(float x, float y) {
this.x = Math.round(x);
this.y = Math.round(y);
}
}
/**
* Extract a signature from its JSON encoding and redraw it as an image.
*
* @param jsonEncoding the JSON representation of the signature
* @param output the destination stream for the image
* @throws IOException if a problem writing the signature
*/
public static void generateSignature(String jsonEncoding, OutputStream output)
throws IOException {
output.write(redrawSignature(extractSignature(jsonEncoding)));
output.close();
}
/**
* Extract the signature lines and points from the JSON encoding.
*
* @param jsonEncoding the JSON representation of the signature
* @return the retrieved lines and points
*/
private static List<List<Point>> extractSignature(String jsonEncoding) {
List<List<Point>> lines = new ArrayList<List<Point>>();
Matcher lineMatcher =
Pattern.compile("(\\[(?:,?\\[-?[\\d\\.]+,-?[\\d\\.]+\\])+\\])").
matcher(jsonEncoding);
while (lineMatcher.find()) {
Matcher pointMatcher =
Pattern.compile("\\[(-?[\\d\\.]+),(-?[\\d\\.]+)\\]").
matcher(lineMatcher.group(1));
List<Point> line = new ArrayList<Point>();
lines.add(line);
while (pointMatcher.find()) {
line.add(new Point(Float.parseFloat(pointMatcher.group(1)),
Float.parseFloat(pointMatcher.group(2))));
}
}
return lines;
}
/**
* Redraw the signature from its lines definition.
*
* @param lines the individual lines in the signature
* @return the corresponding signature image
* @throws IOException if a problem generating the signature
*/
private static byte[] redrawSignature(List<List<Point>> lines) throws IOException {
BufferedImage signature = new BufferedImage(
SIGNATURE_WIDTH, SIGNATURE_HEIGHT, BufferedImage.TYPE_BYTE_GRAY);
Graphics2D g = (Graphics2D)signature.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, signature.getWidth(), signature.getHeight());
g.setColor(Color.BLACK);
g.setStroke(new BasicStroke(2, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g.setRenderingHint(
RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Point lastPoint = null;
for (List<Point> line : lines) {
for (Point point : line) {
if (lastPoint != null) {
g.drawLine(lastPoint.x, lastPoint.y, point.x, point.y);
}
lastPoint = point;
}
lastPoint = null;
}
ByteArrayOutputStream output = new ByteArrayOutputStream();
ImageIO.write(signature, IMAGE_FORMAT, output);
return output.toByteArray();
}
}
C# Rendering
You can render an image from the signature JSON text on the server.
The following shows how to do this in .NET 4.5 C#, thanks to Daniel Knight.
You would call this code as follows
and it returns a base64 encoded byte array as a string:
GetBase64Png(jsonEncoding, width, height);
using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web.Http;
public class GraphicsController : ApiController
{
[HttpGet]
[ActionName("GetBase64Png")]
public string GetBase64Png([FromUri] string linesGraphicJSON, [FromUri] int width, [FromUri] int height)
{
return Draw2DLineGraphic(new JavaScriptSerializer().Deserialize<Signature>(linesGraphicJSON), width, height);
}
private string Draw2DLineGraphic(I2DLineGraphic lineGraphic, int width, int height)
{
//The png's bytes
byte[] png = null;
//Create the Bitmap set Width and height
using (Bitmap b = new Bitmap(width, height))
{
using (Graphics g = Graphics.FromImage(b))
{
//Make sure the image is drawn Smoothly (this makes the pen lines look smoother)
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
//Set the background to white
g.Clear(Color.White);
//Create a pen to draw the signature with
Pen pen = new Pen(Color.Black, 2);
//Smooth out the pen, making it rounded
pen.DashCap = System.Drawing.Drawing2D.DashCap.Round;
//Last point a line finished at
Point LastPoint = new Point();
bool hasLastPoint = false;
//Draw the signature on the bitmap
foreach (List<List<double>> line in lineGraphic.lines)
{
foreach (List<double> point in line)
{
var x = (int)Math.Round(point[0]);
var y = (int)Math.Round(point[1]);
if (hasLastPoint)
{
g.DrawLine(pen, LastPoint, new Point(x, y));
}
LastPoint.X = x;
LastPoint.Y = y;
hasLastPoint = true;
}
hasLastPoint = false;
}
}
//Convert the image to a png in memory
using (MemoryStream stream = new MemoryStream())
{
b.Save(stream, ImageFormat.Png);
png = stream.ToArray();
}
}
return Convert.ToBase64String(png);
}
public class Signature : I2DLineGraphic
{
public List<List<List<double>>> lines { get; set; }
}
interface I2DLineGraphic
{
List<List<List<double>>> lines { get; set; }
}
}
In the Wild
This tab highlights examples of this plugin in use "in the wild".
None as yet.
To add another example, please contact me (wood.keith{at}optusnet.com.au)
and provide the plugin name, the URL of your site, its title,
and a short description of its purpose and where/how the plugin is used.
Quick Reference
A full list of all possible settings is shown below.
Note that not all would apply in all cases. For more detail see the
documentation reference page.
$(selector).signature({
background: '#ffffff', // Colour of the background
color: '#000000', // Colour of the signature
thickness: 2, // Thickness of the lines
guideline: false, // Add a guide line or not?
guidelineColor: '#a0a0a0', // Guide line colour
guidelineOffset: 25, // Guide line offset from the bottom
guidelineIndent: 10, // Guide line indent from the edges
// Error message when no canvas
notAvailable: 'Your browser doesn\'t support signing',
scale: 1, // A scaling factor for rendering the signature (only applies to redraws).
syncField: null, // Selector for synchronised text field
syncFormat: 'JSON', // The output respresentation: 'JSON' (default), 'SVG', 'PNG', 'JPEG'
svgStyles: false, // True to use style attribute in SVG
change: null // Callback when signature changed
});
$.kbw.signature.options // Access settings for all instances
$(selector).signature('option', settings) // Change the instance settings
$(selector).signature('option', name, value) // Change an instance setting
$(selector).signature('option') // Retrieve the instance settings
$(selector).signature('option', name) // Retrieve an instance setting
$(selector).signature('enable') // Enable the signature functionality
$(selector).signature('disable') // Disable the signature functionality
$(selector).signature('destroy') // Remove the signature functionality
$(selector).signature('clear') // Erase any signature
$(selector).signature('isEmpty') // Determine if there is no signature
$(selector).signature('toDataURL') // Convert the signature to an image in a data: URL
$(selector).signature('toJSON') // Convert the signature to JSON
$(selector).signature('toSVG') // Convert the signature to SVG
$(selector).signature('draw', sig) // Re-draw the signature from JSON, SVG, or a data: URL
Usage
Include the jQuery and jQuery UI libraries and CSS in the head section of your page.