Click here to Skip to main content
11,790,946 members (63,272 online)
Click here to Skip to main content

ASP.NET Web Painting TOOL using HTML 5

, 22 Jan 2015 CPOL 29.7K 1.5K 40
Rate this:
Please Sign up or sign in to vote.
ASP.NET Drawing and Painting Using HTML5 CANVAS


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>

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

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.

javascript Declaration Part

//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;
            if (DrawingTypes == "FreeDraw" || DrawingTypes == "Erase") {
            else {
                ctx.clearRect(0, 0, canvas.width, canvas.height);

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() {
        Colors = document.getElementById("SelectColor").value;
        ctx.fillStyle = "#" + Colors;
        switch (DrawingTypes) {
            case "FillRect":
                ctx.rect(rect.startX, rect.startY, rect.w, rect.h);
            case "FillCircle":
                ctx.arc(rect.startX, rect.startY, radius_New, rect.w, rect.h);
            case "Images":
                ctx.drawImage(imageObj, rect.startX, rect.startY, rect.w, rect.h);
            case "DrawText":
                ctx.font = '40pt Calibri';
                ctx.fillText($('#txtInput').val(), rect.startX, rect.startY);
            case "FreeDraw":
                ctx.moveTo(prevX, prevY);
                ctx.lineTo(currX, currY);
                ctx.strokeStyle = "#" + Colors;
                ctx.lineWidth = $('#selSize').val();
//                ctx.beginPath();
//                ctx.moveTo(drawx, drawy);
//                ctx.rect(drawx, drawy,  6, 6);
//                ctx.fill();
            case "Erase":
                ctx.moveTo(prevX, prevY);
                ctx.lineTo(currX, currY);<
                ctx.strokeStyle = "#FFFFFF";
                ctx.lineWidth = 6;
                //                ctx.beginPath();
                //                ctx.moveTo(drawx, drawy);
                //                ctx.rect(drawx, drawy,  6, 6);
                //                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,', '');
                  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.

   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);

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.


Initial release: 2014/07/09.


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


About the Author

syed shanu
Team Leader
India India

His Blog

Syed Shanu is basically from Madurai, Tamil Nadu, India.He was been working in South Korea for past 8 years. He started programming with Basic Language and C language from his high school at 1999.In 2005 he completed his Master of Computer Application. He started his working Career from Dec 2004 with ASP.

He has 9+ years of Experience in Microsoft Technologies.

His work experience with Language and Technology start’s from ASP and SQL Server, Then VB.NET and C# for PDA Application, Touch Screen Application Development, Desktop Application, ASP.NET Web Application Development, MVC and WPF.

He loves to work with Microsoft technology as he started to work on .Net Frame Work version from 1.0 to 4.5.

He had worked with HMI (Human Machine Interface) programs like PLC, Nutrunner Tools, and Sensor programs, RFID programs, Barcode programs and etc.

He usually uses his free time to spend with his Family and go outing. He loves photography and Hiking.

ASP.NET Article of the Day

1) Title : Draw ASP.NET Bar Chart Using HTML5 and jQuery Date : July 8, 2015
2) Title : ASP.NET Web Photo Editing Tool using HTML 5 Date : July 8, 2015
3) Title : MVC AngularJS and WCF Rest Service For Mind Reader Quiz Date : May 18, 2015
4) Title : AngularJS Shopping Cart Using MVC and WCF Rest Service Date : April 10, 2015
5) Title : Insert select update delete in with Simple Log
6) Title : Project Scheduling Using ASP.Net GridView Date : December 26, 2014
7) Title : ASP.NET Web Painting Tool using HTML 5 Date : September 16, 2014

You may also be interested in...

Comments and Discussions

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
mvpsyed 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
mvpsyed 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
mvpsyed 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
professionalsyed shanu22-Dec-14 18:33 
GeneralRe: Pencil option on page load Pin
archana50622-Dec-14 18:56
memberarchana50622-Dec-14 18:56 
QuestionNIce Pin
Member 1061462015-Oct-14 22:18
memberMember 1061462015-Oct-14 22:18 
GeneralMy vote of 5 Pin
Mihai MOGA13-Aug-14 1:45
professionalMihai MOGA13-Aug-14 1:45 
GeneralRe: My vote of 5 Pin
syed shanu17-Aug-14 15:10
membersyed 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
membersyed 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
membersyed 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
membersyed shanu8-Jul-14 22:32 
GeneralMy vote of 5 Pin
yousafzai amazai8-Jul-14 21:37
memberyousafzai amazai8-Jul-14 21:37 
GeneralRe: My vote of 5 Pin
syed shanu8-Jul-14 21:38
membersyed shanu8-Jul-14 21: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
Web03 | 2.8.1509028.1 | Last Updated 22 Jan 2015
Article Copyright 2015 by syed shanu
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid