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.
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.
<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..
window. Onload=function(){ }
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.
// To create canvas const canvas=document.getElementById("myCanvas"); ctx=canvas.getContext("2d"); // canvas height and width ctx.canvas.width=window.innerWidth - 230; ctx.canvas.height=window.innerHeight - 70;
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.
// eventlisteners for touchevents and mouseevents canvas.addEventListener('touchstart',startPos); canvas.addEventListener('touchmove',draw); canvas.addEventListener('touchend',endPos); canvas.addEventListener('mousedown',startPos); canvas.addEventListener('mouseup',endPos); canvas.addEventListener('mousemove',draw); 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:
// coordinates of cursor function getPos(event){ coord.x=event.pageX- canvas.offsetLeft; coord.y=event.pageY- canvas.offsetTop; }
Above code will help us tracking the mouse position and will retrieve x and y coordinates.
Handle "mousemove" event:
// called when mousemoves function draw(event){ //if not painting then return if (!painting) return; ctx.beginPath(); ctx.moveTo(coord.x,coord.y); getPos(event); ctx.lineTo(coord.x,coord.y); ctx.stroke(); }
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:
// called when mouseup function endPos(event){ if(painting){ ctx.closePath(); painting=false; } if (event.type!='mouseout') { restore_array.push(ctx.getImageData(0,0,canvas.width,canvas.height)); index+=1; console.log(restore_array); } }
Whenever mouse is up, cursor will stop putting pixels on canvas.
Undo functionality:
For better understanding, visit following YouTube video..
// undo document.getElementById('btnUndo').addEventListener('click',function(){ undo_last(); });
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..
function undo_last(){ if(index<=0){ clearcanvas(); } else{ index--; restore_array.pop(); ctx.putImageData(restore_array[index],0,0); } }
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:
function clearcanvas() { if(index<=-1){ ctx.clearRect(0, 0, canvas.width, canvas.height); return; } else{ ctx.fillStyle='white'; ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.fillRect(0,0,canvas.width,canvas.height); restore_array=[]; index=-1; } }
For clearing canvas, we will simply paint our canvas with white color. Also will make restore_array variable an empty array.
Color Picker 🌈:
// color document.getElementById('colorChange').addEventListener('change',function(){ ctx.strokeStyle=document.getElementById('colorChange').value; });
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 🖋:
// pen size document.getElementById('penSize').addEventListener('change',function(){ ctx.lineWidth=document.getElementById('penSize').value; });
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:
// pencil document.getElementById('btnPencil').addEventListener('change',function(){ ctx.lineWidth=document.getElementById('penSize').value; ctx.strokeStyle=document.getElementById('colorChange').value; });
Here "btnPencil" is id of pen button we created in html code.
Fill bucket:
// fill document.getElementById('btnBucket').addEventListener('click',function(){ ctx.fillStyle=document.getElementById('colorChange').value; ctx.fillRect(0,0,canvas.width,canvas.height); });
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:
// eraser document.getElementById('btnEraser').addEventListener('click',function() { ctx.lineWidth=document.getElementById('penSize').value; ctx.strokeStyle='white'; });
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:
1 Comments
Great
ReplyDelete