Saturday, August 27, 2011

HTML5 Canvas Tag

  
The canvas element can be used for rendering graphs, game graphics, or other visual images on the fly. Canvas is currently a "2D" base for drawing on using JavaScript. "3D API" is not supported yet. To use canvas element; you must define the canvas tag and then "draw shapes using Javascript functions".

The definition of the canvas element is like this:
<canvas id="mycanvas" height="200" width="200"></canvas>

this is a blank white space that you can draw. Once you define the tag, you can draw on it using the 2D drawing context. You can get the drawing context using .getContext('2d') function. Using 2D drawing context you can draw rectangle, path, text, gradients and images.

You can "draw a rectangle" like this:
function draw_rectange() {
  var canvas = document.getElementById("mycanvas");
  var drawingContext = canvas.getContext("2d");
  drawingContext.fillStyle = "#FF0000";
  drawingContext.fillRect(40, 30, 120, 80);
}



The fillRect(x, y, width, height) function draws a rectangle filled with the current fill style. x and y are the coordinates where the rectangle will be placed. width and height are the sizes of the rectangle.

The fillStyle property can be "a CSS color", "a pattern", or "a gradient". The default fillStyle is solid black.

Click to draw rectangle
Your browser does not support the canvas element.


Internet Explorer 7 and 8 require the third-party explorercanvas library. Internet Explorer 9 supports <canvas> natively.

See Also:

0 comments:

Post a Comment