简体   繁体   中英

Looping a grid in canvas HTML5 with “gaps” between squares?

I want to create 5x5 grid with 40x40px squares and 4px gaps between them, here's a picture:

http://i.stack.imgur.com/hu96a.png

So I intended to do something like this:

$(document).ready(function(){
    var ctx = document.getElementById('grid').getContext('2d');
    for (var y = 0; y < 5; y++) {
        for (var x = 0; x < 5; x++) {
            ctx.fillStyle = "rgb(200,0,0)";
            ctx.fillRect ((40*y)+4*(y+1),(40*x)+4*(x+1),40*(y+1)+4*(y+1),40*(x+1)+4*(x+1));
        };
    };
});

But it did not work, I guess there is a simpler way to do it but i just dont know how! How can I achieve the desired result?

Thanks!

See the Fiddle ,

and the code:

$(document).ready(function(){
    var ctx = document.getElementById('grid').getContext('2d');
    ctx.fillStyle = "rgb(200,0,0)";
    ctx.beginPath();    
    for (var x = 0, i = 0; i < 5; x+=44, i++) {
        for (var y = 0, j = 0; j < 5; y+=44, j++) {            
            ctx.rect (x, y, 40, 40);
        }
    }
    ctx.fill();
    ctx.closePath();
});

Another way:

$(document).ready(function(){
    var ctx = document.getElementById('grid').getContext('2d');
    ctx.fillStyle = "rgb(200,0,0)";    
    for (var x = 0, i = 0; i < 5; x+=44, i++) {
        for (var y = 0, j = 0; j < 5; y+=44, j++) {            
            ctx.fillRect (x, y, 40, 40);
        }
    }
});

In both cases I removed ctx.fillStyle from the for block to improve performance since changes in canvas's state machine slows the drawing process.

EDIT :

As pointed by markE in comments, you can use the following approach too:

$(document).ready(function(){
    var ctx = document.getElementById('grid').getContext('2d');
    var size = 40;
    var offset = 4;

    ctx.fillStyle = "rgb(200,0,0)";
    for (var x = 0; x < 5; x++) {
        for (var y = 0; y < 5; y++) {            
            ctx.fillRect (x*(size+offset), y*(size+offset), size, size);
        }
    }
});

It's just a matter of personal styling!

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