TrinityTuts

HTML5 based web application for drawing using canvas

Last updated on March 13th, 2020 at 12:22 pm

HTML5 is the latest technology in web today. We create lots of interesting thing with HTML5.  In this post i explain you how to create a simple HTML5 based web application for drawing using canvas.

HTML5 Canvas

HTML5 Canvas is used to draw graphics on fly using javascript. The canvas element is only a container for graphics. You must use a script to actually draw the graphics. Canvas has several methods for drawing paths, boxes, circles, text, and adding images. To learn more about canvas follow this link.

Example: To write some thing inside canvas use this

<canvas id="paintSamp1" style="height: 150px;width:350px; margin:auto;"></canvas>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
  var canvasa = document.getElementById('paintSamp1');
  var context1 = canvasa.getContext('2d');
 
  context1.font = 'normal 18px Arial';
  context1.textAlign = 'center';
  context1. textBaseline = 'middle';
  context1.fillStyle = 'red';  // a color name or by using rgb/rgba/hex values
  context1.fillText('Welcome to trinity tuts!', 150, 50); // text and position
</script>

In this above example i first create canvas tag and set height and width and assign id to canvas. After this i include jQuery from google cdn. Now inside <script> first i find canvas in document i need to write something after that call some predefined method like font, textAlign etc. to make my word look nice.

Now i explain you how to make a simple web based paint application

Create a <canvas> inside body.

<canvas id="drawingPaper" width="560" height="280"></canvas>

Create some option we used for drawing like pen size, clear canvas, eraser etc.

<div>
			<button id="clrcanvas">Clear Canvas</button>
			<button id="erasecanvas">Eraser</button>
			<button id="pencanvas">Pen</button>
			
			<div class="colordiv">
				Select Color
				<ul class="color">
					<li><span rel="#cb3594" >Purple</span></li>
					<li class="selectedColor"><span rel="#FF0000" >Red</span></li>
					<li><span rel="#659b41" >Green</span></li>
					<li><span rel="#ffcf33" >Yello</span></li>
				 
				</ul>
			</div>

			<div class="sizediv">
				Select Size
				<ul class="size">
					<li class="selectedColor"><span rel="5" >Small</span></li>
					<li><span rel="12" >Medium</span></li>
					<li><span rel="20" >Large</span></li>
				</ul>
			</div>
		</div>

Include jQuery Library file.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Now we write some javascript code to get or application working.

<script type="text/javascript">
            window.onload = function() {
                $('.selectedColor').trigger('click');
            }
            $(function() {               
      
                c = document.getElementById('drawingPaper')
                context = c.getContext("2d");
                
                $('#drawingPaper').mousedown(function(e) {
                    var mouseX = e.pageX - this.offsetLeft;
                    var mouseY = e.pageY - this.offsetTop;
                    paint = true;
                    addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);
                    redraw();
					$('body').css('cursor', 'default');
                });
                $('#drawingPaper').mousemove(function(e) {
                    if (paint) {
                        addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop, true);
                        redraw();
						$('body').css('cursor', 'default');
                    }
                });
                $('#drawingPaper').mouseup(function(e) {
                    paint = false;
                });
                $('#drawingPaper').mouseleave(function(e) {
                    paint = false;
                });
                var clickX = new Array();
                var clickY = new Array();
                var clickDrag = new Array();
                var paint;
                var curColor;
                
                

                $('.color li').click(function() {
                    $(this).siblings('li').removeClass('selectedColor');
                    $(this).addClass('selectedColor');
                    curColor = $(this).children('span').attr('rel');
                    
                });

                var cursize;
                $('.size li').click(function() {
                    $(this).siblings('li').removeClass('selectedColor');
                    $(this).addClass('selectedColor');
                    cursize = $(this).children('span').attr('rel');
                });
                var clickSize = new Array();

                var clickColor = new Array();
				var curTool;
				$("#erasecanvas").click(function(){
					curTool = "eraser";
				});
				
				$("#pencanvas").click(function(){
					curTool = "";
				});
				
                function addClick(x, y, dragging)
                {
                    clickX.push(x);
                    clickY.push(y);
                    clickDrag.push(dragging);
					if(curTool == "eraser"){
						clickColor.push("white");
					}else{
						clickColor.push(curColor);
					}
                    clickSize.push(cursize);
                }

                function redraw() {
                    
                    context.save();
                    context.beginPath();
                    context.rect(0, 0, context.canvas.width, context.canvas.height);
                    context.clip();

                    context.lineJoin = "round";

                    for (var i = 0; i < clickX.length; i++) {
                        context.beginPath();
                        if (clickDrag[i] && i) {
                            context.moveTo(clickX[i - 1], clickY[i - 1]);
                        } else {
                            context.moveTo(clickX[i] - 1, clickY[i]);
                        }
                        context.lineTo(clickX[i], clickY[i]);
                        context.closePath();
                        context.strokeStyle = clickColor[i];
                        context.lineWidth = parseInt(clickSize[i]);
                        context.stroke();
                    }
                    context.restore();
                }
				
				
				$('#clrcanvas').click(function(){
					context.clearRect(0, 0, c.width, c.height);
				});
				
            });



        </script>

In above code first i get my selected color to draw image so i trigger event to get that thing.

window.onload = function() {
                $('.selectedColor').trigger('click');
            }

Now get our selected color i get my canvas ready to draw picture on it

 c = document.getElementById('drawingPaper')
 context = c.getContext("2d");

Now we need to handle some events over canvas like

When user mouse is down and move over canvas you need to start create image or when user mouse is up and leave you need to stop. In above code i create two main function which are responsible to get mouse position and to draw image.

                function addClick(x, y, dragging)
                {
                    clickX.push(x);
                    clickY.push(y);
                    clickDrag.push(dragging);
					if(curTool == "eraser"){
						clickColor.push("white");
					}else{
						clickColor.push(curColor);
					}
                    clickSize.push(cursize);
                }

                function redraw() {
                    
                    context.save();
                    context.beginPath();
                    context.rect(0, 0, context.canvas.width, context.canvas.height);
                    context.clip();

                    context.lineJoin = "round";

                    for (var i = 0; i < clickX.length; i++) {
                        context.beginPath();
                        if (clickDrag[i] && i) {
                            context.moveTo(clickX[i - 1], clickY[i - 1]);
                        } else {
                            context.moveTo(clickX[i] - 1, clickY[i]);
                        }
                        context.lineTo(clickX[i], clickY[i]);
                        context.closePath();
                        context.strokeStyle = clickColor[i];
                        context.lineWidth = parseInt(clickSize[i]);
                        context.stroke();
                    }
                    context.restore();
                }

Complete Code:

<!DOCTYPE html>
<html>
    <head>
        <title>Demo - HTML5 based web application for drawing using canvas</title>
    </head>
    <body>
        
        <div id="canvasDiv" style="border: 1px solid; width: 560px; height:280">
            <canvas id="drawingPaper" width="560" height="280"></canvas>

        </div>
        <style>
            .color li {list-style: none; width: 150px; border:1px solid #999; text-align: center; cursor: pointer}
            .size li {list-style: none; width: 150px; border:1px solid #999; text-align: center; cursor: pointer}
            .selectedColor{border:2px solid #000 !important;}
        </style>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <script type="text/javascript">
            window.onload = function() {
                $('.selectedColor').trigger('click');
            }
            $(function() {               
      
                c = document.getElementById('drawingPaper')
                context = c.getContext("2d");
                
                $('#drawingPaper').mousedown(function(e) {
                    var mouseX = e.pageX - this.offsetLeft;
                    var mouseY = e.pageY - this.offsetTop;
                    paint = true;
                    addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);
                    redraw();
					$('body').css('cursor', 'default');
                });
                $('#drawingPaper').mousemove(function(e) {
                    if (paint) {
                        addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop, true);
                        redraw();
						$('body').css('cursor', 'default');
                    }
                });
                $('#drawingPaper').mouseup(function(e) {
                    paint = false;
                });
                $('#drawingPaper').mouseleave(function(e) {
                    paint = false;
                });
                var clickX = new Array();
                var clickY = new Array();
                var clickDrag = new Array();
                var paint;
                var curColor;
                
                

                $('.color li').click(function() {
                    $(this).siblings('li').removeClass('selectedColor');
                    $(this).addClass('selectedColor');
                    curColor = $(this).children('span').attr('rel');
                    
                });

                var cursize;
                $('.size li').click(function() {
                    $(this).siblings('li').removeClass('selectedColor');
                    $(this).addClass('selectedColor');
                    cursize = $(this).children('span').attr('rel');
                });
                var clickSize = new Array();

                var clickColor = new Array();
				var curTool;
				$("#erasecanvas").click(function(){
					curTool = "eraser";
				});
				
				$("#pencanvas").click(function(){
					curTool = "";
				});
				
                function addClick(x, y, dragging)
                {
                    clickX.push(x);
                    clickY.push(y);
                    clickDrag.push(dragging);
					if(curTool == "eraser"){
						clickColor.push("white");
					}else{
						clickColor.push(curColor);
					}
                    clickSize.push(cursize);
                }

                function redraw() {
                    
                    context.save();
                    context.beginPath();
                    context.rect(0, 0, context.canvas.width, context.canvas.height);
                    context.clip();

                    context.lineJoin = "round";

                    for (var i = 0; i < clickX.length; i++) {
                        context.beginPath();
                        if (clickDrag[i] && i) {
                            context.moveTo(clickX[i - 1], clickY[i - 1]);
                        } else {
                            context.moveTo(clickX[i] - 1, clickY[i]);
                        }
                        context.lineTo(clickX[i], clickY[i]);
                        context.closePath();
                        context.strokeStyle = clickColor[i];
                        context.lineWidth = parseInt(clickSize[i]);
                        context.stroke();
                    }
                    context.restore();
                }
				
				
				$('#clrcanvas').click(function(){
					context.clearRect(0, 0, c.width, c.height);
				});
				
            });



        </script>

		<div>
			<button id="clrcanvas">Clear Canvas</button>
			<button id="erasecanvas">Eraser</button>
			<button id="pencanvas">Pen</button>
			
			<div class="colordiv">
				Select Color
				<ul class="color">
					<li><span rel="#cb3594" >Purple</span></li>
					<li class="selectedColor"><span rel="#FF0000" >Red</span></li>
					<li><span rel="#659b41" >Green</span></li>
					<li><span rel="#ffcf33" >Yello</span></li>
				 
				</ul>
			</div>

			<div class="sizediv">
				Select Size
				<ul class="size">
					<li class="selectedColor"><span rel="5" >Small</span></li>
					<li><span rel="12" >Medium</span></li>
					<li><span rel="20" >Large</span></li>
				</ul>
			</div>
		</div>
    </body>
</html>