HTML 5 has a very nice drawing API in the form of new Canvas element. Canvas is used for rendering graphs, game graphics, or other visual
images on the fly. Canvas is a rectangular area that we can add to our
HTML5 page. In this article, we shall learn how to draw a shape on the HTML 5 Canvas and save it as image on the server.
Introduction of HTML 5
As per Wikipedia, HTML5 is a language for structuring and presenting content for the World Wide Web, and is a core technology of the Internet originally proposed by Opera Software.[1] It is the fifth revision of the HTML standard (created in 1990 and standardized as HTML4 as of 1997[2]) and as of November 2011 is still under development. Its core aims have been to improve the language with support for the latest multimedia while keeping it easily readable by humans and consistently understood by computers and devices (web browsers, parsers, etc.). HTML5 is intended to subsume not only HTML 4, but XHTML 1 and DOM2HTML (particularly JavaScript) as well.
Read more about HTML 5
here.
What is Canvas in HTML 5?
HTML 5 has a drawing API in the form of new Canvas element. Canvas is used for rendering graphs, game graphics, or other visual images on the fly. Canvas is a rectangular area that we can add to our HTML5 page.
Objective
In this article, we shall learn how to draw a shape on the HTML 5 Canvas element and save it as image on the server.
First we are going to create a HTML 5 page and my code of html 5 looks like below
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Saving Canvas to .png file on the server</title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.2.min.js"
temp_src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.2.min.js" type="text/javascript"></script>
<script type="text/Javascript" language="Javascript">
function drawShapes() {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.fillStyle = "Blue";
context.fillRect(0, 0, 200, 200);
context.beginPath();
context.lineWidth = "4";
context.strokeStyle = "Green";
context.fillStyle = "Yellow";
context.arc(150, 100, 50, 20, Math.PI * 2, false);
context.stroke();
context.fill();
}
</script>
</head>
<body onLoad="drawShapes()">
<canvas id="myCanvas" width="200" height="200"></canvas>
<input type="button" id="btnSave" name="btnSave" value="Save the canvas to server" />
<script type="text/javascript">
// Send the canvas image to the server.
$(function () {
$("#btnSave").click(function () {
var image = document.getElementById("myCanvas").toDataURL("image/png");
image = image.replace('data:image/png;base64,', '');
$.ajax({
type: 'POST',
url: 'CanvasSave.aspx/UploadImage',
data: '{ "imageData" : "' + image + '" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
alert('Image saved successfully !');
}
});
});
});
</script>
</body>
</html>
In the above code snippet, we have a HTML 5 Canvas element with id as myCanvas
with width and height 200. OnLoad
event of the body element we are calling drawShapes
javaScript function. In this function, we have first found out the canvas element using document.getElementById
by passing the canvas id.
Using that object we have created the context in 2D style (3D drawing is currently on its way) and then created a drawing on the canvas something like below picture.
Remember that I have used jQuery as well on the page and this sample doesn't work in IE 9 on my laptop, so you may need to run this in the Firefox or Google Chrome.
On click of the button "Save the canvas to server", we have attached a jQuery function. In that function, we have found the canvas element and toDataUrl
method by passing the image/png
that dictates that we want to save this canvas as .png file and then replaced some content to empty (just a trick to overcome some properties written in the image variable by toDataUrl
mehtod). Then we have sent Ajax request to the server on CanvasSave.aspx page that has UploadImage
method (static WebMethod). Notice the type
, contentType
and dataType
parameters values of the .ajax method.
The CanvasSave.aspx.cs page
Notice that there below code snippet is the code behind not the .aspx code as the .aspx page code will be blank.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Web.Script.Services;
using System.Web.Services;
[ScriptService]
public partial class Canvas1 : System.Web.UI.Page
{
static string path = @"E:\ITFundaCorp\TUTORIALS\Web Programming\HTML5\";
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod()]
public static void UploadImage(string imageData)
{
string fileNameWitPath = path + DateTime.Now.ToString().Replace("/", "-").Replace(" ", "- ").Replace(":", "") + ".png";
using (FileStream fs = new FileStream(fileNameWitPath, FileMode.Create))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
byte[] data = Convert.FromBase64String(imageData);
bw.Write(data);
bw.Close();
}
}
}
}
Couple of points to note.
1. Notice the namespace used
using System.IO;
using System.Web.Script.Services;
using System.Web.Services;
2. The class attribute
[ScriptServices]
3. UploadImage
method attribute and definition. [WebMethod]
and it is Static in nature.
In the UploadImage
method, we have dynamically generated the file name based on current date and time. After that we have used FiileStream
object by passing the path of the file and action to do and then used BinaryWriter to convert imageData string to the image.
Notice that this image will be saved as .png, I couldn't saved it as .jpg; perhaps that is not supported yet.
Once you have saved the image, it will be saved on the specified path as .png image same as below picture.
Wow, nice!. So now you must have appreciating the power of HTML 5 and JavaScript. As far as I know it was not possible in earlier version of HTML obviously as there was no Canvas element. Of course it was being done using Flash and Silverlight but think about the dependency of the plug-ins and kind of effort you used to put to do this.
Hope you liked it, keep learning and sharing stuffs.
Thanks for reading, if you liked it do not forget to share this with your friends and colleagues.
Reference
Of course I have learnt all these using Internet and a HTML 5 book called "HTML 5 Solutions".