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
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.
The HTML 5 Canvas page
<!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.
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
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]
publicpartialclassCanvas1 : System.Web.UI.Page
{
staticstring path = @”E:\ITFundaCorp\TUTORIALS\Web Programming\HTML5\”;
protectedvoid Page_Load(object sender, EventArgs e)
{
}
[WebMethod()]
publicstaticvoid UploadImage(string imageData)
{
string fileNameWitPath = path + DateTime.Now.ToString().Replace(“/”, “-“).Replace(” “, “- “).Replace(“:”, “”) + “.png”;
using (FileStream fs = newFileStream(fileNameWitPath, FileMode.Create))
{
using (BinaryWriter bw = newBinaryWriter(fs))
{
byte[] data = Convert.FromBase64String(imageData);
bw.Write(data);
bw.Close();
}
}
}
}
using System.IO; using System.Web.Script.Services; using System.Web.Services;
2. The class attribute [ScriptServices]
UploadImage
method attribute and definition. [WebMethod]
and it is Static in nature.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.