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
, 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, 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 are 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 for easy understanding 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>
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 which need to be used and initialized the Canvas
. I 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. 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 rectangle
, Circle
, Text
, etc. If user needs 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
, 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
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 MouseDown
method call, I store all the points like mouse X, Mouse y, 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 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 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
, 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, I used 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 complete; I have finally made a simple web-based painting tool.
If you like my article, please leave me a comment.
History
- 9th July, 2014: Initial release