Game Development Reference
In-Depth Information
for (var row = 0; row < numberOfRows; row++) {
context.moveTo(0, row * this.cellSize);
context.lineTo(gridWidth, row * this.cellSize);
}
context.stroke();
}
Wow! That is a really big chunk of code. So, what do we do here?
For the rectangle around the grid, we simply use the
context.strokeRect()
function. The rectangle starts
in the upper-left corner of the canvas, which has the coordinates (0, 0). The width and height for the
rectangle is the grid width and height.
For the grid itself, we need something more like a pencil; thankfully the drawing context API works a lot like
guiding a pencil across a sheet. First we have to pick up the pencil, metaphorically speaking. We tell the
context that we start our drawing with
context.beginPath()
. After this, we move the pencil to where we
want to start drawing the line. We also keep in mind that
moveTo
will move the pencil to a point without
drawing the line, and
lineTo
actually draws a line.
Now we still have to draw the grid. First, we will draw the columns. We calculate the number of columns by
dividing the width of the grid, which we set when initializing the grid class, by the
cellSize
, which was also
set at that point. The rest is pretty much just looping over the amount of columns that we have, and always
moving the pencil to the top and drawing a line to the bottom.
We use the exact same principle for drawing the rows. You might want to go over the lines closely and think
about all the parameters. We believe that it might be good to leave a little bit of the crunching up to you!
Now, what is
context.stroke()
for? Both methods,
lineTo()
and
moveTo()
, just push orders into a stack.
Whenever those methods are called, they are not directly executed. So without the
context.stroke()
,
nothing except the frame would appear because the
strokeRect()
method actually creates the path and
draws it all in one method call.
This is why we also called
context.beginPath()
. This method lets us create a new path and also clears
the stack. So when we call
context.stroke()
, we draw all the lines that we have created since
context.beginPath()
.
So, what do we have so far? We can now exchange the
clearCanvas()
in the ready function with a
draw()
and we will be able to see our grid when we open the
index.html
file in a browser, as shown in Figure 4-5.