I'm new to javascript and canvas, but not entirely new to programming (I have some HTML/PHP experience).
I've always had an interest in web games that use grids, so after taking a few javascript courses online, I found some javascript code that dynamically created hexagonal grids of canvas objects.
I've been playing around with the code, adding click events to highlight the hex you're on, trying to put random numbers on the hexes to depict numbers of "units" etc. Sort of mocking up what a game might look like, just for the learning experience.
One thing that I've been trying to do, and I can't seem to figure out, is how to define canvas objects in an array, so that I can reference them by row/column. It seems like it would be much easier, in the context of a game, to reference a grid cell by row/column so that you can do actions based on that location.
I'm using ocanvas.js to create canvas objects, so ideally I'd love to be able to define a grid cell as:
hex[row][col] = canvas.display.polygon({
x: x0,
y: y0,
sides: 6,
radius: this.radius,
rotation: 0,
fill: fillColor,
stroke: "outside 1px #000",
row: row,
col: col,
zIndex: "back",
selected: false
});
hex[row][col].add();
However, I've noticed that mutlidimensional arrays don't work in javascript like they do in PHP. In PHP, you don't have to predefine the scope of an array. You can just do:
$array = [];
$array[1][5] = "foo";
And it'll put that value in the [1][5] position. In my hex code here: http://tny.cz/14282e49 about 3/4 down I have a comment showing that I want to call my hex[col][row] object... but I'm always getting "Uncaught TypeError: Cannot read property '5' of undefined" errors, where '5' is the column its trying to access.
So, this is a 2 part question:
1) Am I not defining my hex
array correctly to access the canvas objects like that?
2) Is there a better way that I'm just not seeing, to access specific canvas objects in a column/row grid format?