Paint App using HTML, CSS & JS [ Tutorial ]

In this tutorial, we’ll be creating a simple paint program in the web browser, with HTML5, CSS and JavaScript. We’ll create a toolbar, containing a color picker and tools like pencil, fill, eraser, etc. App will allow the user to paint within the canvas element and even save the image. It will also allow user to undo the changes made on canvas.




First, Try the example:

Before getting started with the tutorial, let’s take a look at the actual paint app running in the web browser.


Starting with web page:
We will look at JavaScript code only. Source code of project is available on our GitHub account. Click here --> GitHub Repository 

Creating Canvas in HTML:
For this we have to use canvas tag in html code. We will give id to canvas so that we can create context for canvas in JavaScript code. 
 
  1. <canvas id="myCanvas"></canvas>

Canvas created in above code will serve as our drawing surface. All paint commands will be issued against the canvas element.  

Loading page:
We now have a web page with canvas element. Now we will use some logic for loading the page. There are variety of methods but we will use simplest one. We will use window's "onload" function in following way..

  1. window. Onload=function(){
  2. }

Initializing canvas:

From now on, understanding upcoming code snippets, you should have knowledge of HTML5 Canvas. 

To learn basics of HTML5, visit the link below...

For this we have to use canvas tag in html code. We will give id to canvas so that we can create context for canvas in JavaScript code. 
 
  1. // To create canvas
  2. const canvas=document.getElementById("myCanvas");
  3. ctx=canvas.getContext("2d");
  4.  
  5. // canvas height and width
  6. ctx.canvas.width=window.innerWidth - 230;
  7. ctx.canvas.height=window.innerHeight - 70;
  8.  

In the above code, we’ll also automatically adjust the width and height of the canvas to size to the window. This allows us to adjust the paint area according to the window size.

Handle mouse movements:

Now we will add event listeners to handle mouse movements.
  1. // eventlisteners for touchevents and mouseevents
  2.  
  3. canvas.addEventListener('touchstart',startPos);
  4. canvas.addEventListener('touchmove',draw);
  5. canvas.addEventListener('touchend',endPos);
  6.  
  7. canvas.addEventListener('mousedown',startPos);
  8. canvas.addEventListener('mouseup',endPos);
  9. canvas.addEventListener('mousemove',draw);
  10. canvas.addEventListener('mouseout',endPos);

Line no. 3,4,5 will handle touch events.

Line no. 7,8,9,10 will handle mouse events like, mousedown, mouseup, mousemove and mousemove.

The first listener is to handle the "mousedown" event. This shows that mouse is clicked on canvas.
The second listener is to handle the "mouseup" event. It is opposite of "mousedown" event.
The next listener is to handle the “mousemove” event. It will allow us to paint as the mouse is moved across the screen. 
The "mouseout" event occurs when mouse pointer comes out from canvas.

"startPos","endPos","draw","endPos" functions will be called based on occurred  event.

Track position of mouse cursor:
  1. // coordinates of cursor
  2. function getPos(event){
  3.  
  4. coord.x=event.pageX- canvas.offsetLeft;
  5. coord.y=event.pageY- canvas.offsetTop;
  6. }


Above code will help us tracking the mouse position and will retrieve x and y coordinates.

Handle "mousemove" event:

  1. // called when mousemoves
  2. function draw(event){

  3.  
  4. //if not painting then return
  5. if (!painting) return;
  6.  
  7. ctx.beginPath();
  8. ctx.moveTo(coord.x,coord.y);
  9. getPos(event);
  10. ctx.lineTo(coord.x,coord.y);
  11. ctx.stroke();
  12.  
  13. }
  14.  
If mouse is not down then function call will return to caller, otherwise it will start drawing. 
First getpos() function will get current x and y co-ordinates of mouse, then it will draw a line from the canvas’s current draw point to the mouse’s  x and y coordinate. As the mouse moves across the screen, this method will put, drawing pixels along the way.

Above code will continuously draw as the mouse moves, until user releases the mouse button.

Handle "mouseup" event:
  1. // called when mouseup
  2. function endPos(event){
  3. if(painting){
  4. ctx.closePath();
  5. painting=false;
  6. }
  7. if (event.type!='mouseout') {
  8. restore_array.push(ctx.getImageData(0,0,canvas.width,canvas.height));
  9. index+=1;
  10. console.log(restore_array);
  11. }
  12. }
Whenever mouse is up, cursor will stop putting pixels on canvas.

Undo functionality:

For better understanding, visit following YouTube video..


  1. // undo
  2. document.getElementById('btnUndo').addEventListener('click',function(){
  3. undo_last();
  4. });

Above code shows that, we are accessing button created with id "btnundo" and we have added "click" event listener on it. Event will trigger and call undo_last() function

In code snippet of "mouseup" event at line no. 8, we have used restore_array as a variable to store copy of recent strokes. When "mouseout" is not occurring, it will store copy of strokes in variable and increase index (variable represents size of restore_array variable) by 1.

Whenever user will click on undo button, undo() function will be called..
  1. function undo_last(){
  2. if(index<=0){
  3. clearcanvas();
  4. }
  5. else{
  6. index--;
  7. restore_array.pop();
  8. ctx.putImageData(restore_array[index],0,0);
  9. }
  10. }

If size of restore_array is less than or equal to 0, then it means there is nothing on canvas and we will clear canvas.
If above condition is false, for removing the last stored stroke, it will decrease size of index variable by 1 and also will pop effect of last stroke.

Clear Canvas button:
  1. function clearcanvas() {
  2. if(index<=-1){
  3. ctx.clearRect(0, 0, canvas.width, canvas.height);
  4. return;
  5. }
  6. else{
  7. ctx.fillStyle='white';
  8. ctx.clearRect(0, 0, canvas.width, canvas.height);
  9. ctx.fillRect(0,0,canvas.width,canvas.height);
  10. restore_array=[];
  11. index=-1;
  12. }
  13. }
For clearing canvas, we will simply paint our canvas with white color. Also will make restore_array variable an empty array.

Color Picker 🌈:
  1. // color
  2. document.getElementById('colorChange').addEventListener('change',function(){
  3. ctx.strokeStyle=document.getElementById('colorChange').value;
  4. });
Whenever user will choose color from color picker, it will set as drawing color. Here "colorchange" is id of color picker created in html code.

Pen size 🖋:
  1. // pen size
  2. document.getElementById('penSize').addEventListener('change',function(){
  3. ctx.lineWidth=document.getElementById('penSize').value;
  4. });
When user will change pen size it will be set as linewidth of pen. Here "penSize" is id of slider we use to change size.

Pen tool:
  1. // pencil
  2. document.getElementById('btnPencil').addEventListener('change',function(){
  3. ctx.lineWidth=document.getElementById('penSize').value;
  4. ctx.strokeStyle=document.getElementById('colorChange').value;
  5. });
Here "btnPencil" is id of pen button we created in html code.

Fill bucket:
  1. // fill
  2. document.getElementById('btnBucket').addEventListener('click',function(){
  3. ctx.fillStyle=document.getElementById('colorChange').value;
  4. ctx.fillRect(0,0,canvas.width,canvas.height);
  5. });
This code simply involves calling the "context.fillStyle" to select a color and then calling "context.fillRect()" to paint whole canvas. Here "btnBucket" is id of button created for filling canvas.

Eraser tool:
  1. // eraser
  2. document.getElementById('btnEraser').addEventListener('click',function() {
  3. ctx.lineWidth=document.getElementById('penSize').value;
  4. ctx.strokeStyle='white';
  5. });
  6.  
For creating eraser tool, we have to set stroke style to white, its that simple.😊

Conclusion:

HTML5 provides powerful set of technologies for creating the powerful web-based applications. With the HTML5 canvas element, we can create a large variety of graphical applications, including charts, animations, games, and many more. In this way we created paint app using HTML, CSS & JS.

See demonstration video:



Download source code:

Find source code here --> Paint App

Author: Nikita Choudhari



 

Post a Comment

1 Comments