Author

Hi there!

I'm Anil Kumar M.S. A technology enthusiast living in Mysore, India. I'm Passionate about .Net, Web Apps, Cloud, Application design and Architecture, Ux, Javascript and Windows Phone.

A Microsoft Certified Technology Specialist and also a Professional Developer in .Net 4 Web. I like travelling, doing Adventure & Love food.

Let's be friends !



Webpage : www.msanil.com
×

Wednesday, October 05, 2011

Introduction to Canvas in HTML5

Wednesday, October 05, 2011
The canvas element is a newly introduced element and is a part of HTML5. It allows dynamic scripting and rendering of 2D shapes and bitmap images.

Canvas actually is like a drawing board on which you can draw something. It will have a height and width. Now, you might have a question, “how do I write on it?

Well, the answer is very simple.
You can write your JavaScript code and your code will have access to the entire canvas region. You can use a full set of drawing functions provided similar to any other API’S which provides 2D drawing functions. You can build Graphs, animations, games and image compositions.

What are the possibilities?

Well, I would say the possibilities are infinite. Here are few links which shows what can be achieved using a HTML5 canvas and some JavaScript code.

http://www.effectgames.com/demos/canvascycle/

http://bomomo.com/

http://n96.org/

Note: HTML5 is not yet an official standard, and no browsers have full HTML5 support. But all major browsers (Safari, Chrome, Firefox, Opera, and Internet Explorer) continue to add new HTML5 features to their latest versions. Make sure you are running the above demos on a browser that supports HTML5.

How can we use it?

Just like any other html element on html, you can have a canvas element.


Your browser does not support the canvas element if you are seeing this.


How can I write a rectangle on above canvas?
var c=document.getElementById("myCanvas");
var obj=c.getContext("2d");
obj.fillStyle="#FF0000";
obj.fillRect(0,0,150,75);

Result of above

HTML5 Canvas output

In above example, the JavaScript code first refers to the id of the canvas and then
The c.getContext("2d") object is a built-in HTML5 object, with many functions to draw lines, boxes, circles, characters and images. The last two lines draw a red filled rectangle inside the canvas.

Instead of Rectangle, if you want to draw a circle, just replace the” obj.fillRect(0,0,150,75);
“ with below code
obj.beginPath();
obj.arc(70,18,15,0,Math.PI*2,true);
obj.closePath();
obj.fill(); 

Let us understand some more interesting things of HTML5 & Canvas in near future.
Author : Anil Kumar M.S
A technology enthusiast living in Mysore, India.
You can connect with me on Twitter @MSGuyTweets or on Facebook.
Email me at ms.anil.kumar@gmail.com


Was this post useful?