Create a Signature Painting Drawing App using Javascript
Tags: javascript, webdev, beginners, tutorial
Published: 2022-03-22 10:13:21

Hmm... So let's start with what are the toolset we will be using to accomplish this task... ! So we are going to be using canvas, That's it and javascript for the interaction part... ! If you just want the code you can just scroll down to find all the code at once...



## 1) First we will be creating a blank template of our web page and place the canvas tag
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2a8o7s9jjjzrlb54nxh4.png)

Then we will access the canvas in our javascript using getElementById and set the height and width of our canvas to window height and width divided by 2.


 ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u7sia1x00ve0dpuv7und.png)

Which will be looking something like this.. For visibility purposes I have set background color of body to black

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2oc0a28z1ga5d1iek4bm.png)
 

Next is to handle mouse events

## 2) Handling Mouse Events

In javascript we have the access to the mouse events such as mouseup, mousedown, mousemove etc within document or we can apply it on different set of elements individually ! So I am going to apply this to our canvas and we do so by addEventListener to a specific element which accepts to parameters.
```
element.addEventListener("event_name", callback function()");
```

Here the callback function will run whenever this event -> event_name get's triggered.. ! In this case it's the mouse move event

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/twb5umvn2kruemvj6psk.png)


this **e** in the function() is required to get the current position of **x** and **y** of the mouse

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1qh3x660pklogd39nxg2.png)


So now let us create two variables outside of the eventlistener and set our mouseX and mouseY to e.clientX (returns current position of X in x coords ) and e.clientY ( returns current position of mouse in Y coords ) 

**Note: In javascript there is no negative x and y position. (0, 0) in canvas means top left, top right point in the canvas**

Now let's draw a line in canvas using mousemove events. In general you would draw a line in canvas like this

```


ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(300, 150);
ctx.stroke();

```

But we are going to replace the third and fourth line in two different events. 

Now we need to bring two more events the first is mousedown and mouseup. The working of these events are self explanatory.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rym3nsvwrf4bi7i7lonz.png)
 

 We also need a variable **isDrawing** to keep track whether the user is holding the mouse click.

So in the mouse down event we have,
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3jgpb2jdygjgsxdnwf1d.png)

and here we are not writing lineTo because that's going to changing every second when our mouse is moving.

So in mousemove event we have,
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i40izsxsx5gzrxykfwpl.png)
 
Now you can open up the page in your browser and see that you are drawing 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k3cwjn9yjmfndcikbiai.png)


But here comes are isDrawing variable because in this we can't control when we have to draw, so we do the following
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w1ntjwtf01i3v1b1z9qp.png)
 


First we declared a variable called isDrawing, in mousedown function we set that drawing = true and in mousemove function we are checking if isDrawing is true, if it is so then we are drawing, after we release our mouse, **mouseup** event get's triggered and we are not drawing any more ! 
 


## 3) To save the canvas as png

```
 function downloadCanvas() {
            var imageData = canvas.toDataURL("image/png");
            let anchorTag = document.createElement("a");
            document.body.appendChild(anchorTag);
            anchorTag.href = imageData;
            anchorTag.download = "imageData";
            anchorTag.click();
            document.body.removeChild(anchorTag);
}

```

This is a block of code that just creates a element and set some props and converts the canvas to a image and downloads it !, you can just memorize this because it can be used in any canvas without changing the code !

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qrsdi34f0kkfhhjvfze3.png)

Now we can just create a button to download the picture... !
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g0c0rdlzs7pkwfc98w8d.png)
 
So, *Congratulations* you have just created a web app to write signatures and download it in a png format.. ! 

## 4) Challenge Time

My challenge to you is to modify this code and add feature to sign in different colors etc. ! and comment your modified code so that everyone can see and learnn !! Thank you for reading this... !

Here is the full code !

```
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            background-color: black;
        }
    </style>
</head>

<body>
    <canvas id="canvas"></canvas>

    <button onclick="downloadCanvas();">Save</button>

    <script>
        const canvas = document.getElementById("canvas");
        const ctx = canvas.getContext('2d');
        canvas.width = window.innerWidth / 2;
        canvas.height = window.innerHeight / 2;
        canvas.style.background = "white";


        let mouseX = 0;
        let mouseY = 0;


        let isDrawing = false;
        canvas.addEventListener("mousedown", function (e) {
            isDrawing = true;

            ctx.beginPath();
            mouseX = e.clientX;
            mouseY = e.clientY;
            ctx.moveTo(mouseX, mouseY)

        })

        canvas.addEventListener("mousemove", function (e) {
            if (isDrawing) {
                ctx.lineTo(e.clientX, e.clientY);
                ctx.stroke();
            }

        })

        canvas.addEventListener("mouseup", function (e) {
            isDrawing = false;
        })

        function downloadCanvas() {
            var imageData = canvas.toDataURL("image/png");
            let anchorTag = document.createElement("a");
            document.body.appendChild(anchorTag);
            anchorTag.href = imageData;
            anchorTag.download = "imageData";
            anchorTag.click();
            document.body.removeChild(anchorTag);
        }

    </script>

</body>

</html>
```

Hope you like, share it with your friends too !