0

I'm attempting to draw boxes onto a canvas using JavaScript; my code works, but I'm having trouble with my arrays. Say I have a multi-demensional array called map and it is declared like so:

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

Where 1 is a box and 0 is blank space, but when I run my code the output looks like the following:

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

Is there any way to fix this so the output matches map? My code looks like this:

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

And the HTML is as follows:

<!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 Answer 1

5

You've just mixed up your rows and columns

try switching map[ax][ay]==1 to map[ay][ax]==1

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.