HTML and CSS Reference
In-Depth Information
Retrieving the 2D Context
Finally, we need to get a reference to the 2D context so we can manipulate it. HTML5
Canvas is designed to work with multiple contexts, including a proposed 3D context.
However, for the purposes of this topic, we only need to get the 2D context:
var context = theCanvas.getContext("2d");
The drawScreen() Function
It's time to create actual Canvas API code. Every operation we perform on Canvas will
be through the context object, as it references the object on the HTML page.
We will delve into writing text, graphics, and images to HTML5 Canvas in later chap-
ters, so for now, we will only spend a very short time on the code of the drawScreen()
The “screen” here is really the defined drawing area of the canvas, not the whole
browser window. We refer to it as such because within the context of the games and
applications you will write, it is effectively the “window” or “screen” into the canvas
display that you will be manipulating.
The first thing we want to do is clear the drawing area. The following two lines of code
draw a yellow box on the screen that is the same size as the canvas. fillStyle() sets
the color, and fillRect() creates a rectangle and puts it on the screen:
context.fillStyle = "#ffffaa";
context.fillRect(0, 0, 500, 300);
Notice that we are calling functions of the context . There are no screen
objects, color objects, or anything else. This is an example of the im-
mediate mode we described earlier.
Again, we will discuss the text functions of Canvas in the next chapter, but here is a
short preview of the code we will use to put the text “Hello World!” on the screen.
First, we set the color of the text in the same way we set the color of the rectangle:
context.fillStyle = "#000000";
Then we set the font size and weight:
context.font = "20px _sans";
Next, we set the vertical alignment of the font:
context.textBaseline = "top";
Search WWH ::

Custom Search