1

我正在尝试编写一个 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();
4

1 回答 1

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];
    };
}

例子

于 2012-10-31T22:33:45.980 回答