HTML and CSS Reference
In-Depth Information
Though only two of the three attributes ( width and height ) are required, the id attribute is truly
essential for carrying out any drawing with JavaScript. Like the <video> and <audio> tags, content
between the opening and closing <canvas> tags is rendered only if the <canvas> tag is not sup-
ported. One approach is to provide a static image as an alternative, like this:
<canvas id=”myCanvas” width=”300” height=”225”>
<img src=”altCanvas.jpg” width=”300” height=”225” />
If an alternative image is not available, you can substitute explanatory text.
A <canvas> tag on a page without any associated JavaScript is just an empty space on the page. To
start using the canvas area, you'll need to create a variable that targets the <canvas> tag by first
referencing its id value and then setting the context of that canvas to a two-dimensional drawing
space. Here's the starting JavaScript:
<script type=”text/javascript”>
function doCanvas() {
var my_canvas = document.getElementById(“myCanvas”);
var myCanvas_context = my_canvas.getContext(“2d”);
<body onload=”doCanvas();”>
As you can see, one technique is to place the canvas-related function (here, doCanvas() although
you can use any name you like) in the <head> tag and then call it through an onload event handler
in the <body> tag. Once the context of the canvas area is established, you're ready to start drawing.
JavaScript regards the canvas as a grid with the origin of the x and y coordinates in the upper-left
corner. The number of points on the grid corresponds to the stated width and height attributes in
the <canvas> tag. So, in this example there are 300 x points and 225 y points.
To view any <canvas> example, you'll need to use a browser that supports the
tag. As of this writing, these browsers include Firefox 3.0+, Safari 3.2+, Opera
10.1+, and Google Chrome 5.0+. Internet Explorer 9 is expected to support the
<canvas> tag and associated JavaScript API as well.
Say you wanted to draw a black rectangle that started 50 pixels from the top-left corner and was
100 pixels square. For this, you'd use the fillRect() function, which requires four coordinates:
an x and y pair for the upper-left corner and another pair for the lower-right. Here's the code that
would work with the already established canvas context:
myCanvas_context.fillRect(50, 50, 150, 150);
Search WWH ::

Custom Search