Game Development Reference
In-Depth Information
the context is more the API of the canvas to be used with JavaScript. We will explain how to get the
context of a canvas element later.
In the last block, we declare four global variables. The store and grid are two instances of store.js and
grid.js , the two modules that we talked about earlier. The two other variables are needed for the
brick selection.
Now that we have declared all the global variables that we need, the next thing to do is kick off the
application. jQuery provides us with a very handy function that is called once the browser is finished
building the HTML document.
Once the browser is done, we can grab the canvas element and get the drawing context. Without the
context we cannot draw anything on the canvas, so this step is important. When we have the context, we
clear the canvas so that we can be sure nothing is painted on it. The jQuery function and our described
code looks like this:
$(document).ready(function() {
canvas = document.getElementById('grid');
context = canvas.getContext('2d');
clearCanvas();
});
Note For the purpose of this chapter, we assume that there is a canvas element with
the id 'grid' and that the browser supports the 2d context. Normally, you should check
if that's really the case—and if not, react accordingly!
One thing is still missing. What does our little clearCanvas() function look like? It's pretty simple.
function clearCanvas() {
canvas.width = canvasWidth;
canvas.height = canvasHeight;
}
Why did we call it clearCanvas() if it's basically just setting the size of the canvas? It is because every
time you change the size—or set either the width or the height—it will automatically swipe the entire
content of the canvas; even if you set it to the same size it was before. So, we only use it initially to set the
size, but further calls will actually clear the canvas—just like the name of the method. Why is everything
erased on resize? Luckily, that is how the canvas is defined in the specs.
The drawing loop
As explained in the previous section, the canvas provides a pixel grid that can be freely manipulated. By
default, the context of the canvas is blank—just like a blank sheet of paper before you set your pencil on it
for the first time. That means that we have to draw all the elements with the functions that the canvas
context provides. It actually works similar to how you draw with a pencil, but more on that later. It also
 
Search WWH ::




Custom Search