W3C.US

  • Increase font size
  • Default font size
  • Decrease font size
Home Tutorial HTML5 New Elements in HTML5 -- Canvas

New Elements in HTML5 -- Canvas

E-mail Print PDF

The HTML5 specification includes a new element type: Canvas.

The Canvas element provide an easy way for the webpage designer to draw graphics in javascript or other web-base scripts.

Like the Graphics class in java, to draw graphics in Canvas, need to call/access its relative methods/attributes.

 

 

Define canvas element in HTML:

<canvas id="firstCanvas" width="300" height="300">
If the browser does not support HTML5 canvas, this message will be shown.
</canvas>

Access this canvas in Javascript:

// Get a reference to the element.
var elem = document.getElementById('firstCanvas');

// Always check for properties and methods, to make sure your code doesn't break 
// in other browsers.
if (elem && elem.getContext) {
  // Get the 2d context.
  // Remember: you can only initialize one context per element.
  var context = elem.getContext('2d');
  if (context) {
    // You are done! Now you can draw your first rectangle.
    // You only need to provide the (x,y) coordinates, followed by the width and 
    // height dimensions.
    context.fillRect(0, 50, 300, 200);
  }
}

You can click here to view the sample.

Last Updated on Monday, 21 February 2011 05:18