HTML and CSS Reference
In-Depth Information
To get a reference to the drawing context in your code, you use the getContext() method of the
<canvas> DOM element. Listing 4-2 shows how.
Listing 4-2. Getting a Drawing Context
$(document).ready(function () {
var canvas = $("#MyCanvas").get(0);
var context = canvas.getContext("2d");
As you did in the previous chapter, here you use the jQuery get(0) method to get a reference to the
<canvas> element with ID MyCanvas . As mentioned in Chapter 2, jQuery selectors return a collection of
matching elements. You can retrieve an element from this collection using the get() method by specifying
its zero-based index. In this case, the <canvas> element is selected using its ID. Naturally, the collection has
only one element, and hence index is specified as 0 . You then call the getContext() method of the canvas
object to retrieve its drawing context. The getContext() method takes a parameter indicating the type of
context. A value of 2d indicates two-dimensional drawing content (the only mode currently available).
Once you get the drawing context object, you're ready to draw on the canvas. While performing
drawing operations on the canvas, you need to specify the coordinates where graphics are to be drawn,
and hence you should be aware of the canvas coordinate system. The unit for specifying canvas
coordinates is the pixel. The top-left corner of the canvas has coordinates (0,0). Figure 4-2 explains canvas
coordinates with an example.
Figure 4-2. HTML5 canvas coordinate system
The figure shows a canvas 300 pixels wide and 200 pixels high. The origin of the canvas is at (0,0).
Another point at (150,100) is also shown.
Drawing Lines
Drawing a line is possibly the simplest operation you can perform on a canvas. To draw a line, you need to
perform these operations:
• Shift the current drawing position to a required start point.
Search WWH ::

Custom Search