Game Development Reference
In-Depth Information
means we have to be very aware of the order in which the elements are drawn onto the canvas. Once you
draw something on it, you cannot draw underneath it.
First things first. In this case, we want to draw the grid before we draw any bricks. This is why we decided
to have everything drawn in a recursive sort of way. The application contains a grid. The grid contains all
the bricks. Therefore, the application is only responsible to draw the grid. The grid itself is responsible for
drawing the bricks.
Before we start implementing the basic draw function in application.js , we need to set up a class for the
grid. As it is somehow implied by the previous paragraph, the grid will be responsible for a few things! We
need to add a grid.js to our JavaScript <script> tags in the index.html file, as follows:
<script src="javascripts/jquery.js"></script>
<script src="javascripts/grid.js"></script>
<script src="javascripts/application.js"></script>
The grid.js file will look like this:
var Grid = function(width, height, cellSize) {
this.width = width;
this.height = height;
this.cellSize = cellSize;
this.bricks = [];
}
So, it will basically hold the width and the height of the grid, as well as the brick size. As mentioned, it also
has to manage the bricks, so we use a simple array to save all the bricks that are on the grid.
We will instantiate this class one time in our entry point of the application.js , as follows:
$(document).ready(function() {
canvas = document.getElementById('grid');
context = canvas.getContext('2d');
grid = new Grid(gridWidth, gridHeight, BRICK_SIZE);
clearCanvas();
});
Let's get back to the drawing cycle. The application.js gets a draw() function. This function should be
capable of drawing the current state of the grid, no matter at what time it's called.
So instead of calling clearCanvas() , we go ahead and call draw() to draw the initial state of the application.
$(document).ready(function() {
canvas = document.getElementById('grid');
context = canvas.getContext('2d');
grid = new Grid(gridWidth, gridHeight, BRICK_SIZE);
draw();
});
 
Search WWH ::




Custom Search