Thursday, March 7, 2013

HTML5 Canvas

The <canvas> element is used to draw graphics, on the fly, on a web page.
Draw a red rectangle, a gradient rectangle, a multicolor rectangle, and some multicolor text onto the canvas:
 
What is Canvas?
The HTML5 <canvas> element is used to draw graphics, on the fly, via scripting (usually JavaScript).
The <canvas> element is only a container for graphics. You must use a script to actually draw the graphics.
Canvas has several methods for drawing paths, boxes, circles, characters, and adding images.

Browser Support

Internet ExplorerFirefoxOperaGoogle ChromeSafari
Internet Explorer 9+, Firefox, Opera, Chrome, and Safari support the <canvas> element.
Note: Internet Explorer 8 and earlier versions, do not support the <canvas> element.

Create a Canvas

A canvas is a rectangular area on an HTML page, and it is specified with the <canvas> element.
Note: By default, the <canvas> element has no border and no content.
The markup looks like this:
<canvas id="myCanvas" width="200" height="100"></canvas>
Note: Always specify an id attribute (to be referred to in a script), and a width and height attribute to define the size of the canvas.
Tip: You can have multiple <canvas> elements on one HTML page.
To add a border, use the style attribute:

Example

<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">
</canvas>

Draw Onto The Canvas With JavaScript

All drawing on the canvas must be done inside a JavaScript:

Example

<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillStyle="#FF0000";
ctx.fillRect(0,0,150,75);
</script>
Example explained:
First, find the <canvas> element:
var c=document.getElementById("myCanvas"); 
Then, call its getContext() method (you must pass the string "2d" to the getContext() method):

var ctx=c.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.

The next two lines draw a red rectangle:

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.

0 comments:

Post a Comment