Wednesday, August 27, 2014

Inside UI

Complete UI under one roof

HTML 5.0 Canvas

Posted by deepakgupta On June - 24 - 2009

Introduction

The HTML 5 specification includes lots of new features, one of which is the canvas element. HTML 5 canvas gives you an easy and powerful way to draw graphics using JavaScript. For each canvas element you can use a “context” (think about a page in a drawing pad), into which you can issue JavaScript commands to draw anything you want. Browsers can implement multiple canvas contexts and the different APIs provide the drawing functionality.

Most of the major browsers include the 2D canvas context capabilities - Opera, Firefox, Konqueror and Safari.

The basics of using canvas

Creating a canvas context on your page is as simple as adding the <canvas> element to your HTML document like so:

<canvas id=”myCanvas” width=”300″ height=”150″>
Fallback content, in case the browser does not support Canvas.
</canvas>

You need to define an element ID so you can find the element later in your JavaScript code, and you also need to define the width and height of the canvas.

That’s your drawing pad created, so now let’s put pen to paper. To draw inside your canvas you need to use JavaScript. First you find your canvas element using getElementById, then you initialize the context you want. Once you do that, you can start drawing into the canvas using the available commands in the context API. The following script (try running the example live) draws a simple rectangle into the canvas we defined above:

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

// 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, 0, 150, 100);
}
}

You can choose to include this script inside the head of your document, or in an external file - it’s up to you.

Add A Comment

You must be logged in to post a comment.