Sketch Pad in HTML5 and JavaScript

In this tutorial, we will learn how to make a Sketch Pad In HTML5 and JavaScript that can draw on the browser. Firstly, why we need a sketch pad. Sketch pad may not look useful while working on them using laptops/computer but may prove to be beneficial in case of tablets/iPad/smartphone.

I had seen applications, where SketchPad is used for Signature purposes. It may be a criteria for authenticating the identity of an individual.

The next thing is that these Sketchpads were common in laptop/computer devices, where through mouse the shapes/alphabets can be made. But what about tablets/iPad/smartphones. They have to sense the touch and draw as per the flow of the finger. In the following article, we will be discussing the same.

SketchPad In Action

Now we directly jump into the code and try to understand how it works. It must be kept in mind that the drawing/sketch made on canvas is through the help of Javascript. The simple code which works fine on both computer and tablets/smartphones is as shown.

<html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>SketchPad in HTML5 and Javascript</title>
 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
 <script type="text/javascript">
      $(document).ready(function () {
         initialize();
      });

      function getPosition(mouseEvent, sigCanvas) {
         var x, y;
         if (mouseEvent.pageX != undefined && mouseEvent.pageY != undefined) {
            x = mouseEvent.pageX;
            y = mouseEvent.pageY;
         } else {
            x = mouseEvent.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
            y = mouseEvent.clientY + document.body.scrollTop + document.documentElement.scrollTop;
         }
 
         return { X: x - sigCanvas.offsetLeft, Y: y - sigCanvas.offsetTop };
      }
 
      function initialize() {
         var sigCanvas = document.getElementById("canvasSignature");
         var context = sigCanvas.getContext("2d");
         context.strokeStyle = 'Black';

         var is_touch_device = 'ontouchstart' in document.documentElement;
 
         if (is_touch_device) {
            var drawer = {
               isDrawing: false,
               touchstart: function (coors) {
                  context.beginPath();
                  context.moveTo(coors.x, coors.y);
                  this.isDrawing = true;
               },
               touchmove: function (coors) {
                  if (this.isDrawing) {
                     context.lineTo(coors.x, coors.y);
                     context.stroke();
                  }
               },
               touchend: function (coors) {
                  if (this.isDrawing) {
                     this.touchmove(coors);
                     this.isDrawing = false;
                  }
               }
            };

            function draw(event) {
               var coors = {
                  x: event.targetTouches[0].pageX,
                  y: event.targetTouches[0].pageY
               };

               var obj = sigCanvas;
 
               if (obj.offsetParent) {
                  do {
                     coors.x -= obj.offsetLeft;
                     coors.y -= obj.offsetTop;
                  }

                  while ((obj = obj.offsetParent) != null);
               }

               drawer[event.type](coors);
            }
            sigCanvas.addEventListener('touchstart', draw, false);
            sigCanvas.addEventListener('touchmove', draw, false);
            sigCanvas.addEventListener('touchend', draw, false);

            sigCanvas.addEventListener('touchmove', function (event) {
               event.preventDefault();
            }, false); 
         }
         else {

            $("#canvasSignature").mousedown(function (mouseEvent) {
               var position = getPosition(mouseEvent, sigCanvas);
 
               context.moveTo(position.X, position.Y);
               context.beginPath();

               $(this).mousemove(function (mouseEvent) {
                  drawLine(mouseEvent, sigCanvas, context);
               }).mouseup(function (mouseEvent) {
                  finishDrawing(mouseEvent, sigCanvas, context);
               }).mouseout(function (mouseEvent) {
                  finishDrawing(mouseEvent, sigCanvas, context);
               });
            });
 
         }
      }

      function drawLine(mouseEvent, sigCanvas, context) {
 
         var position = getPosition(mouseEvent, sigCanvas);
 
         context.lineTo(position.X, position.Y);
         context.stroke();
      }

      function finishDrawing(mouseEvent, sigCanvas, context) {
         drawLine(mouseEvent, sigCanvas, context);
 
         context.closePath();
         $(sigCanvas).unbind("mousemove")
                     .unbind("mouseup")
                     .unbind("mouseout");
      }
   </script>
   
</head>
 
<body>
   <h1>Canvas test</h1>
 
   <div id="canvasDiv">
      <canvas id="canvasSignature" width="500px" height="500px" style="border:2px solid #000000;"></canvas>
   </div>
</body>
</html>

Clear from the code, we had written our javascript under <script> tag inside <head> tag in HTML itself. The first function i.e getPosition(mouseEvent,sigCanvas) helps to get the position of X,Y coordinates of mouse click inside the canvas. The initialize() function helps to get the reference to canvas element. This function is important, as it contains the code, which helps to track touch movements. After this, we create draw(event) function to pass coordinates to drawer. We made use of touchstart, touchmove and touched events. Inside the <body> we also apply CSS to provide width and height to canvas. Isn’t it cool.
This will look something like shown below.

Sketch Pad in HTML5 and JavaScript

I hope you loved this article. For more, stay tuned with CodeSpeedy.

Leave a Reply

Your email address will not be published. Required fields are marked *