JavaScript中的奇数数组行为

时间:2015-03-23 01:39:57

标签: javascript arrays html5 canvas html5-canvas

我正在尝试使用JavaScript在画布上绘制框;我的代码工作,但我的数组有问题。假设我有一个名为map的多维数组,它的声明如下:

var map = [ [0,1,1], [0,0,1], [0,1,1], ];

其中1是一个框,0是空格,但是当我运行我的代码时,输​​出如下所示:

0,0,0 1,0,1 1,1,1

有没有办法解决这个问题,所以输出匹配map?我的代码如下所示:

var canvas = null;
var ctx = null;
var x,y,count,inc,ax,ay;


var map = [
    [0,0,0],
    [1,0,1],
    [1,1,1],
];

window.onload = function () {
    canvas = document.getElementById("gameArea");
    ctx = canvas.getContext("2d");
    y=0;
    x=0;
    ax=0;
    ay=0;
    count=0;
    inc=0;

    for(;count<3;count++){
        if(count>0){
            inc = inc + 40;
            console.log("inc:"+inc);
            console.log();
        }

        ay=count;
        console.log("ay:"+ay);
        console.log();

        y = y + inc;
        console.log("y:"+y);
        console.log();

        for(;ax<3;x=x+40,ax++){
            if(map[ax][ay]==1){
                console.log(ax+","+ay)
                console.log(map[ax][ay]);
                console.log();
                ctx.strokeRect(x,y,40,40);
                console.log("block:"+x+","+y);
            }
        }
        console.log();
        x=0;
        y=0;
        ax=0;
    }
};

HTML如下:

<!DOCTYPE html>

<html>
    <head>
        <meta charset="utf-8">
        <title>Single Stage</title>
        <script src="js/game.js" type="text/javascript">
        </script>

        <style type="text/css">
        #gameArea{
            display:block; 
            margin:0 auto; 
            background-color:#FFFFFF;
            border: 1px solid black;
        }
        </style>
    </head>

    <body>
        <canvas id="gameArea"  width='800' height='480'></canvas>
    </body>
</html>

1 个答案:

答案 0 :(得分:5)

您只是混淆了行和列

尝试将map[ax][ay]==1切换为map[ay][ax]==1