Game Development Reference
In-Depth Information
context.beginPath();
context.fillColor = 0;
context.moveTo(0, 0);
context.lineTo(BRICK_SIZE, BRICK_SIZE);
context.lineTo(0, BRICK_SIZE);
context.closePath();
context.fill();
context.restore();
}
Drawing the triangle is also pretty easy. We move our imaginary pencil to the top-left corner after we
started a new path. The next line goes straight to the bottom-right corner; after that, a line to the bottom-
left corner. And after closing and filling the path, we are finished!
Adding bricks to the grid
Yes we know, after writing so much code for the different bricks, it's time to get them on the grid. We
already have the drawing functionality implemented. So, what we still need to do is figure out in which cell
on the grid the user has clicked. Let's walk through that process step by step.
First, we need a callback when the user clicks onto the grid so that we can react upon the click. Since we are
going to have more user interaction and more buttons, we declare a function in the application.js that sets
up all the click handlers. Let's call this function initUI() . It will be called in the ready function as follows:
$(document).ready(function() {
canvas = document.getElementById('grid');
context = canvas.getContext('2d');
grid = new Grid(gridWidth, gridHeight, BRICK_SIZE);
initUI();
draw();
});
So, for the click callback we will use jQuery. It looks like this:
function initUI() {
$(canvas).click(onGridClicked);
}
In the callback we call onGridClicked() , we first have to figure out where the user clicked, because so far,
we only know that the user has clicked somewhere on the grid.
function onGridClicked(event) {
var mouseX = event.offsetX || event.layerX;
 
Search WWH ::




Custom Search