HTML and CSS Reference
In-Depth Information
The number of columns in the grid is calculated using the formula Math.floor(canvas.width / TILE_SIZE) .
That way, if someone resizes the canvas, the number of columns will change automatically.
There are several ways to divide and take the integer part in JavaScript. Math.floor(X / Y) does it; X/Y | 0
works, too, but when Y is a power of 2, it's better to use right bit shift. It works because any bitwise operation removes
the fractional part of a number. Similarly, you can use left bit shift if you need to remove the fractional part and
multiply by a power of 2, using one operator.
The rendering algorithm draws a corresponding sprite for each tile in the tileset, in the same order. The tile
number ID has the coordinates col = id % cols , row =Math.floor (id / cols) in the grid. Each column and row
has a side TILE_SIZE .
Mouse events are the real problem. event.pageX and event.pageY contain absolute coordinates, and so to
determine the canvas coordinates, you have to subtract offsets of each parent in the document object model (DOM):
function BuilderWnd(editor, sprites, canvas) {
this.editor = editor; this.tiles = editor.tiles; this.sprites = sprites; this.canvas = canvas;
this.initMouseEvents(canvas); this.redraw();
BuilderWnd.prototype = {
click: function(x, y) {
var index = (y >> TILE_SIZE_BITS) * this.cols + (x >> TILE_SIZE_BITS)
this.editor.selected = index >= 0 && index < this.tiles.byId.length?
this.tiles.byId[index]: null
initMouseEvents: function(canvas) {
var self = this;
$(canvas).mousedown(function(e) {
var x = e.pageX;
var y = e.pageY;
var t =;
while (t != document.body) {
x -= t.offsetLeft;
y -= t.offsetTop;
t = t.parentNode;
}, y);
redraw: function() {
var canvas = this.canvas
canvas.width = canvas.parentNode.clientWidth;
canvas.height = canvas.parentNode.clientHeight;
this.cols = canvas.width >> TILE_SIZE_BITS
this.rows = canvas.height >> TILE_SIZE_BITS
Search WWH ::

Custom Search