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.
- <!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.
- <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
- <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>
-
-
- var canvas;
- var ctx;
- var x = 75;
- var y = 50;
-
- var WIDTH = 1024;
- var HEIGHT = 740;
-
-
- var Colors="";
- var newPaint = false;
- var DrawingTypes = "";
-
- var radius = 30;
- var radius_New = 30;
-
- rect = {},
-
- drag = false;
-
- 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();
-
- var prevX = 0,
- currX = 0,
- prevY = 0,
- currY = 0;
-
- var imageObj = new Image();
-
- 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 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
- <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 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
-
- 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;
- }
-
- 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;
-
- }
-
-
- 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 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
-
- 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();
-
-
-
-
- break;
- case "Erase":
-
- ctx.beginPath();
- ctx.moveTo(prevX, prevY);
- ctx.lineTo(currX, currY);<
- ctx.strokeStyle = "#FFFFFF";
- ctx.lineWidth = 6;
- ctx.stroke();
- ctx.closePath();
-
-
-
-
- break;
- }
-
- ctx.fill();
-
- }
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.
-
- function ShanuSaveImage() {
- var m = confirm("Are you sure to Save ");
- if (m) {
-
- 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;
- 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 then leave me comments.