How to use HTML5 Canvas

Hi,

If you are an “Action Script” developer you can assume HTML5 canvas element as Graphics Class in which you can draw shapes (line, circle,rectangle) etc.

you can simply create canvas element by writing this code in your body tag

 <canvas id="myCanvas" width="400" height="400"> </canvas>

Canvas doesn’t provide any drawing abilities of its own, We use javascript to draw on it. To draw anything from javascript we have to access canvas, for accessing you can use

 var canvas = document.getElementById("myCanvas");

The getContext(“2d”) method return a built-in HTML5 object(context),which is used to draw paths, circles, characters, images etc using its methods

var context = canvas.getContext("2d");

now you have context you can draw a rectangle using this code

context.fillRect(50,50,100,25);

Full Code will be:

var canvas=document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.fillStyle="#FF0000";
context.fillRect(50,50,100,25);

Hurrey we created our first HTML5 code.

Here is a basic HTML5 template which we will use in next learning sessions

<!DOCTYPE HTML>
<html>
    <head>
        <script>

            window.onload = function(){
                var canvas = document.getElementById("myCanvas");
                var context = canvas.getContext("2d");

                // do stuff here
            };

        </script>
    </head>
    <body>
        <canvas id="myCanvas" width="600" height="400">
        </canvas>
    </body>
</html>

i copied it from this site you will get most of the starting tutorial there, you can also start begin from here.

Advertisements

About Jeetendra Chauhan

I am a s/w developer. love to code
This entry was posted in HTML5 and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s