JavaScript数组数组:未定义的元素

时间:2012-10-19 03:40:46

标签: javascript arrays multidimensional-array

我一直在使用javascript开发一个canvas应用程序,我需要在其中定义一个9格单元格(3x3),并且每个网格中都有一个canvas元素。

问题是,我已经有一个名为grid的数组,其中包含表示每个单元格大小的数据。

var grid = new Array();

grid[0] = {x:[0, elemWidth], y:[0, elemHeight]};
grid[1] = {x:[elemWidth, elemWidth*2], y:[0, elemHeight]};
grid[2] = {x:[(elemWidth*2), sWidth], y:[0, elemHeight]};
grid[3] = {x:[0, elemWidth], y:[elemHeight+1,elemHeight*2]};
grid[4] = {x:[elemWidth, elemWidth*2], y:[elemHeight, elemHeight*2]};
grid[5] = {x:[(elemWidth*2), sWidth], y:[elemHeight, elemHeight*2]};
grid[6] = {x:[0, elemWidth], y:[(elemHeight*2), sHeight]};
grid[7] = {x:[elemWidth, elemWidth*2], y:[(elemHeight*2), sHeight]};
grid[8] = {x:[(elemWidth*2), sWidth], y:[(elemHeight*2), sHeight]};

这会在Chrome检查器上生成以下输出:

inspector output

据我所知,我应该可以使用以下代码获取x和y值

canvas[i].fillRect(grid[i].x[0], grid[i].y[0], grid[i].x[1], grid[i].y[1]);
canvas[i].strokeRect(grid[i].x[0], grid[i].y[0], grid[i].x[1], grid[i].y[1]);

每个都应该给我相应的值。

我无法理解为什么我可以在canvas[0](浏览器上呈现的所有内容)上获得一切正常但是当涉及到后续的canvas[i](i> 0时)将无法呈现虽然HTML为每个canvas元素生成标记,但我得到一个未定义的值。

我做错了声明数组吗?

修改

为了简单和可读性,对代码进行了一些更改:

function createCanvas() {

/* criar grelha aqui */

var sWidth = window.innerWidth; //- 50;
var sHeight = window.innerHeight; //- 50;

var elemWidth = sWidth / 3;
var elemHeight = sHeight / 3;

var grid = new Array();

var row1 = [0, elemHeight];
var row2 = [elemHeight, elemHeight*2];
var row3 = [elemHeight*2, sHeight];

var col1 = [0, elemWidth];
var col2 = [elemWidth, elemWidth*2];
var col3 = [elemWidth*2, sWidth];

grid[0] = [col1, row1];
grid[1] = [col2, row1];
grid[2] = [col3, row1];
grid[3] = [col1, row2];
grid[4] = [col2, row2];
grid[5] = [col3, row2];
grid[6] = [col1, row3];
grid[7] = [col2, row3];
grid[8] = [col3, row3];

for (var i = 0; i < grid.length; i++) {
    var c = document.getElementById('content');
    var newCanvas = document.createElement('canvas');
    newCanvas.setAttribute('id', 'canvas'+i);
    c.appendChild(newCanvas);
    canvas[i] = new Canvas('canvas'+i, 0, function() {});
        canvas[i].clear();
        canvas[i].setAutoResize(true);
        canvas[i].canvasElement.width = elemWidth - 2;
        canvas[i].canvasElement.height = elemHeight - 2;


        canvas[i].fillStyle('#000000');
        canvas[i].strokeStyle('#FFFFFF');

    canvas[i].fillRect(grid[i][0], grid[i][0], grid[i][2], grid[i][3]);
    canvas[i].strokeRect(grid[i][0], grid[i][0], grid[i][4], grid[i][5]);

这段代码比之前只有一点功能

的版本要完整得多

同时我设法得到3个单元格渲染(虽然3个单元格,应该是1x3实际上是2x1,因为不知何故渲染没有正确发生,我认为这可能是一个CSS问题)

EDIT2

我再次对上面的代码进行了一些更改。并且网格数组的新截图展开了视图。 grid array expanded view

0 个答案:

没有答案