Monday, January 28, 2013

HTML5 CANVAS

CANVAS is newly introduced in HTML5. CANVAS is used to render graphics on the fly.

The most common usage are as below


  • It can be used to draw graphics.
  • Make photo compositions.
  • Create animations or even do real-time video processing.



Now let us see the Canvas Element Tag:
<canvas id="canvas1" width="100px" height="100px"> </canvas>

We can have more than one canvas in HTML page. Each can be accessed through their unique (id) attribute. Now the <canvas> can be accessed through DOM as shown below.

<canvas id="canvas_1" width="100px" height="100px"> </canvas>
var vcanvas= document.getElementById("canvas_1");

The canvas is border less. If width and height are not specified it will be 300 pixels wide and 150 pixels high. let us do some examples with <canvas>.style is used in <canvas> to define border

<! Doctype HTML>
<HTML>
<Body>
<canvas id="canvas_1" width="100px" height="100px" style="border:1px solid #000000;"> </canvas>
</Body> </HTML>

Javascript is required to draw something in <canvas>


A button tag is introduced to call the javascript function DrawRectangle().
<button type="button" id="button1" onclick="DarwRectangle()">Click Me</button>

<script>
function DarwRectangle()
{
var canvas= document.getElementById("canvas_1");
var ctx= canvas.getContext("2d");
ctx.fillStyle="#FF0000";
ctx.fillRect(0,0,150,75);
}
</script>
The Output will be like following.

Explanation of the function DrawRectangle()

document.getElementById("canvas_1");
The above line returns the canvas object.

canvas.getContext("2d");

The getContext("2d") object is a built-in HTML5 object, with many properties and methods for drawing paths, boxes, circles, text, images, and more.

ctx.fillStyle="#FF0000";
ctx.fillRect(0,0,150,75);

The fillStyle property can be a CSS color,
a gradient, or a pattern. The default fillStyle is #000000 (black).

The fillRect(x,y,width,height) method draws a rectangle
filled with the current fill style.

More on canvas in Part 2 continued....

No comments: