简体   繁体   中英

JavaScript Loop to create grid on canvas

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/

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

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/

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