Game Development Reference
In-Depth Information
var mouseY = event.offsetY || event.layerY;
var column = Math.floor(mouseX / BRICK_SIZE);
var row = Math.floor(mouseY / BRICK_SIZE);
}
First we read the X and Y position relative to the top-left corner of the canvas element. Every mouse click
triggers a certain event. This event contains a lot of information, including information on the position of the
mouse while clicked. The only problem is that different browsers go by different naming conventions.
WebKit browsers such as Chrome or Safari have an attribute called
offsetX
(or
offsetY
) and Firefox calls
the same value
layerX
(or
layerY
).
For further details, you need to look up the specs of different browsers. But
offsetX
and
layerX
should
cover most major browsers. So to get the
mouseX
value, we take the
offsetX
attribute; and if that is
undefined, we take the
layerX
value. We do this in a one-liner using an OR.
Note
This method is not completely safe because the user might click on the very left
top which would mean that the offsetX is 0 and, therefore, false when it comes to the
OR. But that is a very unlikely case and, therefore, ignored in this simple demo.
After reading the exact mouse position, it's easy to get the cell the user clicked in. All we have to do is
divide the value by the block size. But remember to round the value, or in this case to get more accurate
values we use
Math.floor
. Why? Let's say the user clicks on a pixel left of the third brick in the first row.
He is very close, but still on the second brick. So the value we would get after dividing the
mouseX
by the
BRICK_SIZE
would be something like 2.99. When we round that value, it is 3; but we still want it to be 2.
Therefore, we always bring the value down to a round figure.
Now we need to create a brick on that cell. Let's call and create another function,
createBrickAt(column,
row)
.
The function will look something like this:
function createBrickAt(column, row) {
var brick = new Square();
brick.column = column;
brick.row = row;
grid.addBrick(brick, context);
}
A very straightforward function! First, we create a Square brick. (We'll differentiate between the different
bricks later.) After that, we assign our row and column values to the brick and then we pass it to the grid,
since the grid is supposed to manage all existing bricks. We also pass the context to the grid, so that it
knows where the new bricks should be drawn.
So, what does the grid do with the brick? Thanks to the well-planned base we built, there is not much the
grid has to do.