Categories
JavaScript Web development

JS Simple Signature Pad

Create the Signature Pad and export the file as PNG.

Signature Pad - Vector Image
Do you like this image? Check more images in the store.
*animation opened in the Safari browser.
To see the live output click here.

What do you need to do?

  1. Add HTML
  2. Add CSS
  3. Add JavaScript

Step1.

Add HTML

Create the canvas-wrap:

<div id="canvas-wrap">
<canvas id="canvas"></canvas>   
<div id="buttons">
       <div id="text">Please sign above</div>
       <input type="button" id="download" value="Save as PNG"/>
      <input type="button" id="clear" value="Clear">
    </div>
</div>

Step2.

Add CSS

body {
  background-color: #bee3db;
  height: 100vh;  
}

canvas {  
  background-color: #fff;
  border-radius: 15px;
  border: 5px solid black;
  box-shadow: 5px 4px 5px black;
  
}

#canvas-wrap {
  position: relative;
 
}

 #buttons {
        position: absolute;
        top: 370px;
        left: 170px;
        
      }
#buttons > input {
        padding: 10px;
        background-color: #839791;
        color: white;
        display: block-inline;
        margin-top: 5px;
      }

#text {
  position:relative;
  font-weight: bold;
  left: 25px;
}

Step3.

Add JavaScript

To drawing on the canvas:

var canvas = document.querySelector('canvas');
  canvas.style.position = 'absolute';
  canvas.style.top = "0";
  canvas.style.left = "0";

var ctx = canvas.getContext('2d');
canvas.width = 500;
canvas.height = 350;

ctx.lineWidth = 3;
ctx.lineJoin = ctx.lineCap = 'round';

var isDrawing, lastPoint;

canvas.onmousedown = function(event) {
  isDrawing = true;
  lastPoint = { x: event.clientX, y: event.clientY };
};

canvas.onmousemove = function(event) {
  if (!isDrawing) return;

  ctx.beginPath();
  
  ctx.globalAlpha = 1;
  ctx.moveTo(lastPoint.x, lastPoint.y);
  ctx.lineTo(event.clientX, event.clientY);
  ctx.stroke();
     
  lastPoint = { x: event.clientX, y: event.clientY };
};

canvas.onmouseup = function() {
  isDrawing = false;
};

To clear the canvas:

document.getElementById('clear').addEventListener('click', function() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
      }, false);

To export the file as PNG:

window.onload = function(){
var save = document.getElementById('download');

 save.onclick = function(){
    download(canvas, 'signature.png');
  }

}

function download(canvas, filename) {
  var lnk = document.createElement('a'), e;
  lnk.download = filename;
  lnk.href = canvas.toDataURL("image/png;base64");
  
  if (document.createEvent) {
    e = document.createEvent("MouseEvents");
    e.initMouseEvent("click", true, true, window,
                     0, 0, 0, 0, 0, false, false, false,
                     false, 0, null);

    lnk.dispatchEvent(e);
  } else if (lnk.fireEvent) {
    lnk.fireEvent("onclick");
  }
}

To see the live output check my Codepen.

Enjoy coding!