javascript - 迭代二维数组

时间:2012-10-31 22:27:55

标签: javascript arrays html5 canvas

我正在尝试编写一个javascript程序,在HTML5画布上呈现8x8网格的污垢。但是,当我运行此代码时,它会在运行draw_terrain()函数时抛出错误消息,并且它似乎是blockArray.length组件的问题。有人可以向我解释如何解决这个问题吗?提前谢谢。

//Define initial canvas variables and images

var canvas;
var ctx;
var WIDTH = 800;
var HEIGHT = 800;
var dirt = new Image();
dirt.src = 'dirt.png';

//Function called to initialise canvas variables and run draw on interval

function init(){
    canvas = document.getElementById('myCanvas');
    ctx = canvas.getContext('2d');
    return setInterval(draw, 15);
}

//Function that generates an 8x8 Array called blockArray

function gen_terrain(){

var blockArray = new Array(8);

for(var i=0; i<blockArray.length; i++) {
    blockArray[i] = new Array(8);
    for(var j=0; j<blockArray[i].length; j++){
        blockArray[i][j] = 0;
    };
};
}

//Function that returns a random number between a min and max

function randomRange (min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function draw_terrain(){
    for(var i=0; i<blockArray.length; i++) {
        for(var j=0; j<blockArray[i].length; j++){
            ctx.drawImage(dirt,(n-1)*32,(j-1)*32);
        };
    };
}

function draw(){
    draw_terrain();
}

gen_terrain();
init();

1 个答案:

答案 0 :(得分:1)

你的问题正如其他人所解释的那样,你在使用构建数组的变量在绘制时不会存在。只需将数组声明置于函数之外,您的问题就会消失。

见下面的评论:

function init(){
    canvas = document.getElementById('myCanvas');
    ctx = canvas.getContext('2d');
    return setInterval(draw, 15);
}

//Function that generates an 8x8 Array called blockArray
var blockArray = []; // <== has to be global (outside function).

function gen_terrain(){
    // Not here -> var blockArray = [];
    for(var i=8; i--;) {
        blockArray[i] = [0,0,0,0,0,0,0,0];
    };
}

Example