Click here to Skip to main content
Click here to Skip to main content

ASP.NET Web Painting TOOL using HTML 5

, 7 Aug 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
ASP.NET Drawing and Painting Using HTML5 CANVAS

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 few basics which need to know about HTML5 and 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.

<!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

   <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 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 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
Visit My SHANU C# Blog
Mr.Shanu is a Senior Software Engineer. He’s basically from India and working at South Korea for more than 7 years.


He has 9+ years of Experience in Microsoft Technologies. More than 7 Years of experience in Automation Fields, He has worked in several projects of MES, Automation, ERP and HMI programs like PLC, Sensor, RFID and Nutrunner Tools. He has worked in both Windows based and Web Based projects.


Shanu Love to learn and work with new technology.


His main hobbies are to spend time with Family and to create Different and Innvotive programs and write Article about his program and Share with others.

His Latest Article which he likes most was Windows Form Design at Run Time

His facebook page
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
QuestionPencil option on page load Pinmemberarchana50622-Dec-14 19:30 
AnswerRe: Pencil option on page load Pinprofessionalsyed shanu22-Dec-14 19:33 
GeneralRe: Pencil option on page load Pinmemberarchana50622-Dec-14 19:56 
QuestionNIce PinmemberMember 1061462015-Oct-14 23:18 
GeneralMy vote of 5 PinprofessionalMihai MOGA13-Aug-14 2:45 
GeneralRe: My vote of 5 Pinmembersyed shanu17-Aug-14 16:10 
SuggestionWeb Painting Tool PinmemberMember 999275511-Jul-14 3:37 
GeneralRe: Web Painting Tool Pinmembersyed shanu11-Jul-14 22:16 
QuestionNice Post PinprofessionalManoj Kr. Verma10-Jul-14 20:40 
AnswerRe: Nice Post Pinmembersyed shanu10-Jul-14 20:42 
QuestionNice work PinmemberSmile568-Jul-14 23:29 
AnswerRe: Nice work Pinmembersyed shanu8-Jul-14 23:32 
GeneralMy vote of 5 Pinmemberyousafzai amazai8-Jul-14 22:37 
GeneralRe: My vote of 5 Pinmembersyed shanu8-Jul-14 22:38 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.141223.1 | Last Updated 8 Aug 2014
Article Copyright 2014 by syed shanu
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid