Web Painting Tool Using HTML 5 CANVAS in ASP.Net

This article explains how to develop a web painting tool using the HTML 5 canvas.

 

Tool 
 
Introduction

For a long time I have been planning to develop a web-based painting tool. I have developed a painting tool as a Windows application. But using ASP.NET I find it more difficult to develop a web-based painting tool. Finally using the HTML 5 Canvas I have developed a simple web-based Painting tool. HTML 5 has made my work much easier. It's really fun to work with HTML 5. There are many tutorials available for HTML5 in the internet for those readers interested in learning HTML5, use Google.

Now let's see a basic introduction to the HTML5 Canvas. So what is the HTML5 Canvas? The HTML5 Canvas is an element to draw Graphics on a web page. In a simple way we can say a Canvas is a rectangular container in a web page where we can draw graphics.

To create a web-based painting tool we have used the HTML5 CANVAS Element with JavaScript. We can see the details in the code.

Now let's see a few basics that need to be understoond about HTML5 and the CANVAS Tag.

HTML5: HTML5 is a new version of HTML. HTML5 has cross-platform support, which means that HTML5 can work in a PC, Tablet and a Smartphone. HTML5 should be started with a DOCTYPE for example.

  1. <!DOCTYPE html> <html> <body></body> </html> 

The new features in HTML5 are CANVAS, AUDIO, VIDEO and and so on.

CANVAS

CANVAS is the element for 2D Drawings using JavaScript. The Canvas has methods like drawing paths, rectangles, arcs, text and and so on.

The Canvas Element looks like the following.

  1. <canvas id="canvas" width="400" height="400"></canvas> 

For more details about HTML5 and the CANVAS Tag use Google .There are many interesting things to learn in HTML5.

Using the code

The main purpose is to make the program very simple and easy to use; all the functions have been well commented in the project. I have attached my sample program in this article for more details. Here we will see the procedure to create a Painting Tool using the HTML5 Canvas.

The Canvas is nothing but a container for creating graphics .To create 2D Graphics we need to use JavaScript; here in code we will see it in detail.

Step 1: Create a Canvas ELEMENT and declare the global variables and initialize the Canvas in JavaScript. In the code I have used comments to easily understand the declarations.

HTML Canvas Part

  1. <SECTION style="border-style: solid; border-width: 2px; width: 1024px;">
      <CANVAS HEIGHT=
    "740" WIDTH="1024px" ID="canvas"
  2.      Your browser is not supporting HTML5 Canvas .Upgrade Browser to view this program or check with Chrome or in Firefox.
    </CANVAS>
  3. </SECTION> 

JavaScript Declaration Part

  1. <SCRIPT>  
  2. //public Canvas object to use in all the functions.  
  3. //Main canvas declaration   
  4.     var canvas;  
  5.     var ctx;  
  6.     var x = 75;  
  7.     var y = 50;  
  8.     //Width and Height of the canvas  
  9.     var WIDTH = 1024;  
  10.     var HEIGHT = 740;  
  11.     //    var dragok = false;  
  12. //Global color variable which will be used to store the selected color name.  
  13.     var Colors="";  
  14.     var newPaint = false;  
  15.     var DrawingTypes = "";  
  16.     //Circle default radius size  
  17.     var radius = 30;  
  18.     var radius_New = 30;  
  19.     // Rectangle array  
  20.     rect = {},  
  21.     //drag= false defult to test for the draging  
  22. drag = false;  
  23. // Array to store all the old Shanpes drawing details  
  24.     var rectStartXArray = new Array();  
  25.     var rectStartYArray = new Array();  
  26.     var rectWArray = new Array();  
  27.     var rectHArray = new Array();  
  28.     var rectColor = new Array();  
  29.     var DrawType_ARR = new Array();  
  30.     var radius_ARR = new Array();  
  31.     var Text_ARR = new Array();  
  32.     // Declared for the Free hand pencil Drawing.  
  33.     var prevX = 0,  
  34.     currX = 0,  
  35.     prevY = 0,  
  36.     currY = 0;  
  37.     //to add the Image  
  38.     var imageObj = new Image();  
  39. //Initialize the Canvas and Mouse events for Canvas  
  40.     function init(DrawType) {  
  41.         newPaint = true;  
  42.         canvas = document.getElementById("canvas");  
  43.         x =5;  
  44.         y = 5;  
  45.         DrawingTypes = DrawType;  
  46.         ctx = canvas.getContext("2d");  
  47.         radius = 30;  
  48.         radius_New = radius;  
  49.         canvas.addEventListener('mousedown', mouseDown, false);  
  50.         canvas.addEventListener('mouseup', mouseUp, false);  
  51.         canvas.addEventListener('mousemove', mouseMove, false);  
  52.         imageObj.src = 'images/Afraz.jpg';  
  53.   
  54.         return setInterval(draw, 10);  
  55.     } 

In JavaScript I have declared all the global variables that need to be used and to initialize the Canvas. Have I created a Mouse event for the Canvas. The Mouse event was created to draw exactly where the mouse is clicked inside the Canvas container.

Step 2: Draw and fill a rectangle on the Canvas container using JavaScript. I have used a color picker and by default the selected color will be used for drawing and the user can select a different color.

HTML Drawing Part

Drawing Part

 

  1. <img src="images/rect.png"  onClick="init('FillRect')" />  
  2.      <img src="images/Circle.png"  onClick="init('FillCircle')" />  
  3.  <img src="images/Font.png"  onClick="init('DrawText')" />  
  4.  <img src="images/Pencil.png"  onClick="init('FreeDraw')" />  
  5.  <img src="images/Image.png"  onClick="init('Images')" /> 

I have placed images to draw a rectangle, circle, text and and so on. If the user needs to draw a circle, click on the Circle Image and then draw on the Canvas Container. In the Image Click I call the JavaScript Init Method and pass the drawing type as circle, rectangle and and so on. In the Init method we have created Canvas Mouse events like MouseDown, MouseMove and MouseUp. Here are the JavaScript methods for the mouse events.

JavaScript Mouse Events Part

  1. //Mouse down event method  
  2.     function mouseDown(e) {  
  3.         rect.startX = e.pageX - this.offsetLeft;  
  4.         rect.startY = e.pageY - this.offsetTop;  
  5.         radius_New = radius;  
  6.         prevX = e.clientX - canvas.offsetLeft;  
  7.         prevY = e.clientY - canvas.offsetTop;  
  8.         currX = e.clientX - canvas.offsetLeft;  
  9.         currY = e.clientY - canvas.offsetTop;  
  10.         drag = true;  
  11.     }  
  12.     //Mouse UP event Method  
  13.     function mouseUp() {  
  14.         rectStartXArray[rectStartXArray.length] = rect.startX;  
  15.         rectStartYArray[rectStartYArray.length] = rect.startY;  
  16.         rectWArray[rectWArray.length] = rect.w;  
  17.         rectHArray[rectHArray.length] = rect.h;  
  18.         Colors = document.getElementById("SelectColor").value;  
  19.         rectColor[rectColor.length] = "#" + Colors;  
  20.         DrawType_ARR[DrawType_ARR.length] = DrawingTypes  
  21.         radius_ARR[radius_ARR.length] = radius_New;  
  22.         Text_ARR[Text_ARR.length] = $('#txtInput').val();  
  23.         drag = false;  
  24.          
  25.     }  
  26.   
  27.     //mouse Move Event method  
  28.     function mouseMove(e) {  
  29.         if (drag) {  
  30.             rect.w = (e.pageX - this.offsetLeft) - rect.startX;  
  31.               
  32.              rect.h = (e.pageY - this.offsetTop) - rect.startY;  
  33.              drawx = e.pageX - this.offsetLeft;  
  34.              drawy = e.pageY - this.offsetTop;  
  35.              prevX = currX;  
  36.              prevY = currY;  
  37.              currX = e.clientX - canvas.offsetLeft;  
  38.              currY = e.clientY - canvas.offsetTop;  
  39.             if (drag = true) {  
  40.                 radius_New += 2;  
  41.                  
  42.             }  
  43.             draw();  
  44.             if (DrawingTypes == "FreeDraw" || DrawingTypes == "Erase") {  
  45.             }  
  46.             else {  
  47.                 ctx.clearRect(0, 0, canvas.width, canvas.height);  
  48.             }  
  49.              
  50.         }  
  51.         drawOldShapes();  
  52.     } 

Here in the MouseDown Method call I store all the points like mouse X, Mouse y and and so on in a global variable. In the MouseUp method I store all the past drawing paths in Arrays for all the drawings. In the MouseMove I store all the present path points in a variable and call draw shapes to draw the appropriate  drawings that are selected.

JavaScript Draw Part

  1. //Darw all Shaps,Text and add images   
  2.     function draw() {  
  3.         ctx.beginPath();  
  4.         Colors = document.getElementById("SelectColor").value;  
  5.         ctx.fillStyle = "#" + Colors;  
  6.         switch (DrawingTypes) {  
  7.             case "FillRect":  
  8.                 ctx.rect(rect.startX, rect.startY, rect.w, rect.h);  
  9.                 break;  
  10.             case "FillCircle":  
  11.                 ctx.arc(rect.startX, rect.startY, radius_New, rect.w, rect.h);  
  12.                 break;  
  13.             case "Images":  
  14.                 ctx.drawImage(imageObj, rect.startX, rect.startY, rect.w, rect.h);  
  15.                 break;  
  16.             case "DrawText":  
  17.                 ctx.font = '40pt Calibri';  
  18.                   
  19.                 ctx.fillText($('#txtInput').val(), rect.startX, rect.startY);  
  20.                 break;  
  21.             case "FreeDraw":  
  22.                 ctx.beginPath();  
  23.                 ctx.moveTo(prevX, prevY);  
  24.                 ctx.lineTo(currX, currY);  
  25.                 ctx.strokeStyle = "#" + Colors;  
  26.                 ctx.lineWidth = $('#selSize').val();  
  27.                 ctx.stroke();  
  28.                 ctx.closePath();  
  29. //                ctx.beginPath();  
  30. //                ctx.moveTo(drawx, drawy);  
  31. //                ctx.rect(drawx, drawy,  6, 6);  
  32. //                ctx.fill();  
  33.                 break;  
  34.             case "Erase":  
  35.                 
  36.                 ctx.beginPath();  
  37.                 ctx.moveTo(prevX, prevY);  
  38.                 ctx.lineTo(currX, currY);<  
  39.                 ctx.strokeStyle = "#FFFFFF";  
  40.                 ctx.lineWidth = 6;  
  41.                 ctx.stroke();  
  42.                 ctx.closePath();  
  43.                 //                ctx.beginPath();  
  44.                 //                ctx.moveTo(drawx, drawy);  
  45.                 //                ctx.rect(drawx, drawy,  6, 6);  
  46.                 //                ctx.fill();  
  47.                 break;  
  48.         }  
  49.           
  50.         ctx.fill();  
  51.        // ctx.stroke();  
  52.     } 
In the Draw method I have passed the DrawingType to switch the case. If the selected type is a rectangle then I will draw the rectangle on the Canvas, if the selected type is text then draw the text on the Canvas and so on.

Step 3: Save the Canvas final work as an Image file. In the save image click I call the JavaScript function to save the Canvas Images using jQuery and in the C# code behind is a Webmethod to store the Canvas image to the root folder.

  1. //Save as Image file   
  2.     function ShanuSaveImage() {   
  3.           var m = confirm("Are you sure to Save ");   
  4.           if (m) {   
  5.               // generate the image data   
  6.               var image_NEW = document.getElementById("canvas").toDataURL("image/png");   
  7.               image_NEW = image_NEW.replace('data:image/png;base64,''');  
  8.               $.ajax({  
  9.                   type: 'POST',  
  10.                   url: 'Default.aspx/SaveImage',  
  11.                   data: '{ "imageData" : "' + image_NEW + '" }',  
  12.                   contentType: 'application/json; charset=utf-8',  
  13.                   dataType: 'json',  
  14.                   success: function (msg) {  
  15.                       alert('Image saved to your root Folder !');  
  16.                   }  
  17.               });  
  18.           }        
  19.     } 

Here is the Web Method to store the Canvas image to the root Folder.

  1. [WebMethod()]  
  2.     public static void SaveImage(string imageData)  
  3.     {  
  4.           
  5.         Random rnd = new Random();  
  6.         String Filename = HttpContext.Current.Server.MapPath("Shanuimg" + rnd.Next(12, 2000).ToString() + ".png");  
  7.         string Pic_Path = Filename;//HttpContext.Current.Server.MapPath("ShanuHTML5DRAWimg.png");  
  8.         using (FileStream fs = new FileStream(Pic_Path, FileMode.Create))  
  9.         {  
  10.             using (BinaryWriter bw = new BinaryWriter(fs))  
  11.             {  
  12.                 byte[] data = Convert.FromBase64String(imageData);  
  13.                 bw.Write(data);  
  14.                 bw.Close();  
  15.             }  
  16.         }  
  17.     } 
Points of Interest

Working with HTML5 is really fun. I hope you enjoyed reading my article. I will be happy if someone benefits from my article. My long-time plan is now comlete; I have finally made a simple web-based painting tool.

If you like my article then leave me comments.