简体   繁体   中英

javascript - iterating over bidimensional arrays

I am trying to write a javascript program that renders an 8x8 grid of dirt tiles on an HTML5 canvas. However, when I run this code it throws up error messages when running the draw_terrain() function and it appears to be a problem with the blockArray.length component. Can someone explain to me how to fix this problem? Thanks in advance.

//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();

Your problem, as other people have explained is that the variable you are using the build the array will not exist by the time the draw occurs. Just place your array declaration outside of the function and your issue will go away.

See comment below:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM