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, 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 that we set the color of the rectangle:
context
.
fillStyle
=
"#000000"
;
Then we set the font size and weight:
context
.
font
=
"20px Sans-Serif" ...
Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.