A while back I wrote about touch events and the HTML5 canvas. In writing that post I created a demo of a “signature” field for a web page that could be used on both desktop and mobile browsers. Recently I revisited the e-signature itself and turned it into a standalone jQuery plugin.

Check out the demo page and the source code on GitHub. It’s registered as a Bower package, too!

Update: Clearing the Canvas

Aside from restructuring it as a jQuery plugin, the code remains about the same. I added a few initialization parameters for customizing the signature field - size, color, etc - and fixed one small bug: in Internet Explorer (and Edge), the canvas wouldn’t actually clear when calling the clearCanvas method. This was because I was using a hacky way of clearing a canvas element:

function clearCanvas() {
  canvas.width = canvas.width;
}

This code is bad for several reasons: it can be slow, it is broken in the IE family of browsers, and (without the method name) it is unclear what is actually happening. The solution is to use the clearRect() method of the canvas API, and to render lines properly by calling beginPath() before drawing:

// Clear the canvas
clearCanvas: function() {
  this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
  this._resetCanvas();
},

// Render the signature to the canvas
_renderCanvas: function() {
  if (this.drawing) {
    this.ctx.beginPath();
    this.ctx.moveTo(this.lastPos.x, this.lastPos.y);
    this.ctx.lineTo(this.currentPos.x, this.currentPos.y);
    this.ctx.stroke();
    this.lastPos = this.currentPos;
  }
},