0

What I'm trying to do is fill myCanvas with 32x32 blocks of random colors. I'm using a loop to create the blocks and assign them colors. I've figured out how to get the line to descend on the Y axis as the loop goes on but I can't wrap my head around getting the X axis right.

If you make the canvas larger you will see that lines of blocks 20 blocks long go on to the right.

var c=document.getElementById("myCanvas");
        var ctx=c.getContext("2d");
        for (i = 0; i < 400; i++) {
            var X = i * 32;
            var Y = Math.floor(i / 20) * 32;
            ctx.fillStyle='#'+Math.floor(Math.random()*16777215).toString(16);
            ctx.fillRect(X, Y, 32, 32);
            console.log('X:' + X);
            console.log('Y:' + Y);
        }

I've tried using modulus like this:

if(i % 20 == 0){
X = 0;
}

But it only fixes it when I get multiples of 20 so only the left side of the canvas will be filled with blocks. My problem is wrapping my head around the math involved in getting this done. Sorry I'm pretty tired and new at this :(

Fiddle: http://jsfiddle.net/orwfo7re/

2 Answers 2

1

you were already pretty close with your modulus suggestion! However, your if statement only gets executed when i % 20 == 0, something that for instance is not true for i=21

The solution is to just use var x = (i % 20) * 32 for var x in your algoritm. So:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
for (i = 0; i < 400; i++) {
     var X = (i % 20) * 32;
     var Y = Math.floor(i / 20) * 32;
     ctx.fillStyle='#'+Math.floor(Math.random()*16777215).toString(16);
     ctx.fillRect(X, Y, 32, 32);
}

fiddle: https://jsfiddle.net/MartyB/ur9vug0x/2/

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

Comments

1

Do you mean to do something like this:

var c=document.getElementById("myCanvas");
            var ctx=c.getContext("2d");
            var width = 640;
            var height = 640;

            for (y=0; y< height; y=y+32) {
                for (x=0; x < width; x=x+32) {
                ctx.fillStyle='#'+Math.floor(Math.random()*16777215).toString(16);
                ctx.fillRect(x, y, 32, 32);
                }
            }

1 Comment

Thanks I actually looked into nested loops a little bit, that fixes it to, wish I could make them both answers :(

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.