HTML and CSS Reference
In-Depth Information
The drawScreen() Function
It's time to create actual Canvas API code. Every operation we perform on Canvas will be
through the context object, because it references the object on the HTML page.
We will delve into writing text, graphics, and images to HTML5 Canvas in later chapters, so
for now, we will spend only a short time on the code of the drawScreen() function.
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 );
NOTE
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 immediate mode we described earlier.
Again,wewill discussthetext functions ofCanvas inthenextchapter,buthereisashortpre-
view 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 that we set the color of the rectangle:
context . fillStyle = "#000000" ;
Then we set the font size and weight:
context . font = "20px Sans-Serif" ;
Next, we set the vertical alignment of the font:
context . textBaseline = "top" ;
Finally, we print our text on the screen by calling the fillText() method of the context ob-
ject. The three parameters of this method are text string, x position, and y position:
context . fillText ( "Hello World!" , 195 , 80 );
Search WWH ::




Custom Search