Reputation: 167
I want to create 5x5 grid with 40x40px squares and 4px gaps between them, here's a picture:
https://i.sstatic.net/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!
Upvotes: 0
Views: 1483
Reputation: 2878
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!
Upvotes: 3