Click here to Skip to main content
14,644,129 members
Articles » Web Development » ASP.NET » General » Revisions
Article
Posted 22 Jan 2015

Stats

71.2K views
3.4K downloads
48 bookmarked

ASP.NET Web Painting TOOL using HTML 5

Rate this:
4.83 (25 votes)
Please Sign up or sign in to vote.
4.83 (25 votes)
8 Jul 2014CPOL
ASP.NET Drawing and Painting Using HTML5 CANVAS
This is a new version of the currently published article.

Image 1

Introduction

Long time since I have been planning to develop a web based painting tool. I have developed painting tool using Windows Application. But using ASP.Net I find more difficulty to develop a web based painting tool. Finally with the help of 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 is lots of tutorial available for HTML5 in internet. If readers interested to learn HTML5 use Google.

  Now let’s see a basic intro for HTML5 Canvas. So what is a HTML5 Canvas is. HTML5 CANVAS is an Element which is used to draw Graphics on web page. In a Simple way we can say CANVAS as a Rectangular Container in a web page where we can do draw graphic.

 To create a web based painting tool. We have used HTML5 CANVAS Element with JavaScript. We can see details in Code part.

Now let’s see few basics which need to know about HTML5 and CANVAS Tag.

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

<!DOCTYPE html>
<html>
<body></body>
</html>

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

CANVAS:
The CANVAS is the Element which is used for 2d Drawings using JavaScript. The CANVAS has methods like drawing paths, rectangle, arc, text and etc.

The canvas Element looks like below.

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

For more details about HTML5 and CANVAS Tag use Google .There is lots of interesting things to learn in HTML5.

Using the code

The main aim 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 Steps to create a Painting Tool using HTML5 CANVAS.

CANVAS is nothing but a container where we can create graphics .To create 2d Graphics we need to use JavaScript here in code we will see in detail.

Step 1: Create Canvas ELEMENT and declare the global variables and initialize the canvas in JavaScript. In Code I have used comments to easy understand of declarations.

HTML Canvas Part

<SECTION style="border-style: solid; border-width: 2px; width: 1024px;">
<CANVAS HEIGHT="740" WIDTH="1024px" ID="canvas">

Your browser is not supporting HTML5 Canvas .Upgrade Browser to view this program or check with Chrome or in Firefox.
</CANVAS>
</SECTION>

javascript Declaration Part

<SCRIPT>
//public Canvas object to use in all the functions.
//Main canvas declaration 
    var canvas;
    var ctx;
    var x = 75;
    var y = 50;
    //Width and Height of the canvas
    var WIDTH = 1024;
    var HEIGHT = 740;
    //    var dragok = false;
//Global color variable which will be used to store the selected color name.
    var Colors="";
    var newPaint = false;
    var DrawingTypes = "";
    //Circle default radius size
    var radius = 30;
    var radius_New = 30;
    // Rectangle array
    rect = {},
    //drag= false defult to test for the draging
drag = false;
// Array to store all the old Shanpes drawing details
    var rectStartXArray = new Array();
    var rectStartYArray = new Array();
    var rectWArray = new Array();
    var rectHArray = new Array();
    var rectColor = new Array();
    var DrawType_ARR = new Array();
    var radius_ARR = new Array();
    var Text_ARR = new Array();
    // Declared for the Free hand pencil Drawing.
    var prevX = 0,
    currX = 0,
    prevY = 0,
    currY = 0;
    //to add the Image
    var imageObj = new Image();
//Initialize the Canvas and Mouse events for Canvas
    function init(DrawType) {
        newPaint = true;
        canvas = document.getElementById("canvas");
        x =5;
        y = 5;
        DrawingTypes = DrawType;
        ctx = canvas.getContext("2d");
        radius = 30;
        radius_New = radius;
        canvas.addEventListener('mousedown', mouseDown, false);
        canvas.addEventListener('mouseup', mouseUp, false);
        canvas.addEventListener('mousemove', mouseMove, false);
        imageObj.src = 'images/Afraz.jpg';

        return setInterval(draw, 10);
    }

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

Step 2: Draw and Fill Rectangle on canvas container using JavaScript. I have used color picker by default the selected color will be used for drawing user can select different color.

HTML Drawing Part

Image 2

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

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

javascript Mouse Events Part

 //Mouse down event method
    function mouseDown(e) {
        rect.startX = e.pageX - this.offsetLeft;
        rect.startY = e.pageY - this.offsetTop;
        radius_New = radius;
        prevX = e.clientX - canvas.offsetLeft;
        prevY = e.clientY - canvas.offsetTop;
        currX = e.clientX - canvas.offsetLeft;
        currY = e.clientY - canvas.offsetTop;
        drag = true;
    }
    //Mouse UP event Method
    function mouseUp() {
        rectStartXArray[rectStartXArray.length] = rect.startX;
        rectStartYArray[rectStartYArray.length] = rect.startY;
        rectWArray[rectWArray.length] = rect.w;
        rectHArray[rectHArray.length] = rect.h;
        Colors = document.getElementById("SelectColor").value;
        rectColor[rectColor.length] = "#" + Colors;
        DrawType_ARR[DrawType_ARR.length] = DrawingTypes
        radius_ARR[radius_ARR.length] = radius_New;
        Text_ARR[Text_ARR.length] = $('#txtInput').val();
        drag = false;
       
    }

    //mouse Move Event method
    function mouseMove(e) {
        if (drag) {
            rect.w = (e.pageX - this.offsetLeft) - rect.startX;
            
             rect.h = (e.pageY - this.offsetTop) - rect.startY;
             drawx = e.pageX - this.offsetLeft;
             drawy = e.pageY - this.offsetTop;
             prevX = currX;
             prevY = currY;
             currX = e.clientX - canvas.offsetLeft;
             currY = e.clientY - canvas.offsetTop;
            if (drag = true) {
                radius_New += 2;
               
            }
            draw();
            if (DrawingTypes == "FreeDraw" || DrawingTypes == "Erase") {
            }
            else {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
            }
           
        }
        drawOldShapes();
    }

Here in MouseDown Method call i store all the points like mouse X,Mouse y and etc in a global variable .In MouseUp method i store all the past drawing path in Arrays for all the drawings.In MouseMove  i store all the present path points in variable and call draw Shapes to draw appropriate  drawings which is selected.

javascript Draw Part

  //Darw all Shaps,Text and add images 
    function draw() {
        ctx.beginPath();
        Colors = document.getElementById("SelectColor").value;
        ctx.fillStyle = "#" + Colors;
        switch (DrawingTypes) {
            case "FillRect":
                ctx.rect(rect.startX, rect.startY, rect.w, rect.h);
                break;
            case "FillCircle":
                ctx.arc(rect.startX, rect.startY, radius_New, rect.w, rect.h);
                break;
            case "Images":
                ctx.drawImage(imageObj, rect.startX, rect.startY, rect.w, rect.h);
                break;
            case "DrawText":
                ctx.font = '40pt Calibri';
                
                ctx.fillText($('#txtInput').val(), rect.startX, rect.startY);
                break;
            case "FreeDraw":
                ctx.beginPath();
                ctx.moveTo(prevX, prevY);
                ctx.lineTo(currX, currY);
                ctx.strokeStyle = "#" + Colors;
                ctx.lineWidth = $('#selSize').val();
                ctx.stroke();
                ctx.closePath();
//                ctx.beginPath();
//                ctx.moveTo(drawx, drawy);
//                ctx.rect(drawx, drawy,  6, 6);
//                ctx.fill();
                break;
            case "Erase":
              
                ctx.beginPath();
                ctx.moveTo(prevX, prevY);
                ctx.lineTo(currX, currY);<
                ctx.strokeStyle = "#FFFFFF";
                ctx.lineWidth = 6;
                ctx.stroke();
                ctx.closePath();
                //                ctx.beginPath();
                //                ctx.moveTo(drawx, drawy);
                //                ctx.rect(drawx, drawy,  6, 6);
                //                ctx.fill();
                break;
        }
        
        ctx.fill();
       // ctx.stroke();
    }

In Draw method i have passed the DrawingType to switch  case.If selected type is rectangle i will draw the rectangle on Canvas, if selected type is text draw Text on canvas and etc.

Step 3: Save Canvas final work as Image file.In save image Click i call the javascript function to save the Canvas Images using jQuery and in C# code behind used Webmethod to store the canvas image to the root folder.

  //Save as Image file 
    function ShanuSaveImage() { 
          var m = confirm("Are you sure to Save "); 
          if (m) { 
              // generate the image data 
              var image_NEW = document.getElementById("canvas").toDataURL("image/png"); 
              image_NEW = image_NEW.replace('data:image/png;base64,', '');
              $.ajax({
                  type: 'POST',
                  url: 'Default.aspx/SaveImage',
                  data: '{ "imageData" : "' + image_NEW + '" }',
                  contentType: 'application/json; charset=utf-8',
                  dataType: 'json',
                  success: function (msg) {
                      alert('Image saved to your root Folder !');
                  }
              });
          }      
    }

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

[WebMethod()]
   public static void SaveImage(string imageData)
   {

       Random rnd = new Random();
       String Filename = HttpContext.Current.Server.MapPath("Shanuimg" + rnd.Next(12, 2000).ToString() + ".png");
       string Pic_Path = Filename;//HttpContext.Current.Server.MapPath("ShanuHTML5DRAWimg.png");
       using (FileStream fs = new FileStream(Pic_Path, FileMode.Create))
       {
           using (BinaryWriter bw = new BinaryWriter(fs))
           {
               byte[] data = Convert.FromBase64String(imageData);
               bw.Write(data);
               bw.Close();
           }
       }
   }

Points of Interest

Working with HTML5 is really a fun. Hope you enjoyed while reading my Article. I will be happy if someone gets benefited from my article. My long time plan comes to end today finally i have made a simple web based painting tool.
If you like my article leave me a comments.

History

Initial release: 2014/07/09.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

syed shanu
Team Leader
India India
Microsoft MVP | Code Project MVP | CSharp Corner MVP | Author | Blogger and always happy to Share what he knows to others. MyBlog

My Interview on Microsoft TechNet Wiki Ninja Link

Comments and Discussions

Discussions on this specific version of this article. Add your comments on how to improve this article here. These comments will not be visible on the final published version of this article.
 
QuestionHow to Save to Database Pin
Paolo Santiago9-Jul-17 19:03
MemberPaolo Santiago9-Jul-17 19:03 
GeneralMy vote of 5 Pin
Tridip Bhattacharjee5-Feb-17 21:35
professionalTridip Bhattacharjee5-Feb-17 21:35 
PraiseGreat work :) Pin
Ehsan Sajjad26-Oct-16 9:59
professionalEhsan Sajjad26-Oct-16 9:59 
Questionerase tool missing. Pin
Member 115532685-May-15 20:10
MemberMember 115532685-May-15 20:10 
QuestionHow do you run this? Pin
juan gonzalas3-Mar-15 14:09
Memberjuan gonzalas3-Mar-15 14:09 
AnswerRe: How do you run this? Pin
syed shanu3-Mar-15 14:13
mvasyed shanu3-Mar-15 14:13 
Questionwonderful article! Pin
jackbhanded10-Feb-15 20:29
Memberjackbhanded10-Feb-15 20:29 
QuestionError on first page Pin
Dewey22-Jan-15 18:16
MemberDewey22-Jan-15 18:16 
AnswerRe: Error on first page Pin
syed shanu22-Jan-15 18:27
mvasyed shanu22-Jan-15 18:27 
GeneralRe: Error on first page Pin
Dewey22-Jan-15 21:20
MemberDewey22-Jan-15 21:20 
GeneralRe: Error on first page Pin
syed shanu22-Jan-15 22:11
mvasyed shanu22-Jan-15 22:11 
GeneralRe: Error on first page Pin
Dewey23-Jan-15 23:14
MemberDewey23-Jan-15 23:14 
GeneralRe: Error on first page Pin
peter horwood24-Jan-15 11:08
professionalpeter horwood24-Jan-15 11:08 
QuestionPencil option on page load Pin
archana50622-Dec-14 18:30
Memberarchana50622-Dec-14 18:30 
AnswerRe: Pencil option on page load Pin
syed shanu22-Dec-14 18:33
mvasyed shanu22-Dec-14 18:33 
GeneralRe: Pencil option on page load Pin
archana50622-Dec-14 18:56
Memberarchana50622-Dec-14 18:56 
QuestionNIce Pin
Yuvraj Khose15-Oct-14 22:18
MemberYuvraj Khose15-Oct-14 22:18 
GeneralMy vote of 5 Pin
Ștefan-Mihai MOGA13-Aug-14 1:45
professionalȘtefan-Mihai MOGA13-Aug-14 1:45 
GeneralRe: My vote of 5 Pin
syed shanu17-Aug-14 15:10
mvasyed shanu17-Aug-14 15:10 
SuggestionWeb Painting Tool Pin
Member 999275511-Jul-14 2:37
MemberMember 999275511-Jul-14 2:37 
GeneralRe: Web Painting Tool Pin
syed shanu11-Jul-14 21:16
mvasyed shanu11-Jul-14 21:16 
QuestionNice Post Pin
Manoj Kr. Verma10-Jul-14 19:40
professionalManoj Kr. Verma10-Jul-14 19:40 
AnswerRe: Nice Post Pin
syed shanu10-Jul-14 19:42
mvasyed shanu10-Jul-14 19:42 
QuestionNice work Pin
Smile568-Jul-14 22:29
MemberSmile568-Jul-14 22:29 
AnswerRe: Nice work Pin
syed shanu8-Jul-14 22:32
mvasyed shanu8-Jul-14 22:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.