Thursday, December 1, 2011

Let us play with HTML 5, specially HTML 5 Canvas



<br /> HTML 5<br />



Prerequisites:
All you need to get started with Basic is a modern browser such as Google Chrome, Firefox, Safari, Opera, or IE9, a good working knowledge of JavaScript, and a simple text editor like notepad. 
The HTML5 Canvas element is very similar to HTLM tag like <table>, <span>, <div> with exception that it is contents are rendered with JavaScript. 
<canvas id="myCanvas"></canvas> 

HTML5 Canvas Template 
<!DOCTYPE HTML>
<html>
    <head>
        <script> 
            window.onload = function(){
                var canvas = document.getElementById("myCanvas");
                var context = canvas.getContext("2d"); 
                // do your action here
            }; 
        </script>
    </head>
    <body>
        <canvas id="myCanvas" width="600" height="600">
        </canvas>
    </body>
</html> 

HTML5 Canvas Element Explanation 
The code above will be the base template for all of your future HTML5 Canvas projects.
We can define the height and width of the canvas tag using the height and width attributes,
just like we would with any other HTML tag.
Inside the initializer function we can access the canvas DOM object by its id,
and then get a 2-d context using the getContext() method.

HTML5 Canvas Line Example with Explanation
<!DOCTYPE HTML>
<html>
    <head>
        <style>
            body {
                margin: 0px;
                padding: 0px;
            }
           
            #myCanvas {
                border: 1px solid #9C9898;
            }
        </style>
        <script>
           
            window.onload = function(){
                var canvas = document.getElementById("myCanvas");
                var context = canvas.getContext("2d");
               
                context.moveTo(100, 150);
                context.lineTo(450, 50);
context.strokeStyle = "#ff0000"; // line color
context.lineWidth = 10;
                context.stroke();
            };
        </script>
    </head>
    <body onmousedown="return false;">
        <canvas id="myCanvas" width="578" height="200">
        </canvas>
    </body>
</html>

The moveTo(): It takes two argument, moveTo() method creates a new subpath for the given point. This point becomes the new context point. You can think of the moveTo() method as a way to position your drawing cursor.
The lineTo():It takes two argument, lineTo() method draws a line from the context point to the given point.
The stroke() method assigns a color to the line and makes it visible. Unless otherwise specified, the default stroke color is black.
The strokeStyle = “” To set the color of an HTML5 Canvas line, we can use the strokeStyle property of the canvas context.