[英]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: 我想创建5x5的网格,其中40x40px的正方形之间有4px的间隙,这是一张图片:
http://i.stack.imgur.com/hu96a.png 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. 在这两种情况下,我
ctx.fillStyle
从for
块中删除了ctx.fillStyle
以提高性能,因为画布状态机的更改会减慢绘制过程。
EDIT : 编辑 :
As pointed by markE in comments, you can use the following approach too: 正如markE在评论中指出的那样,您也可以使用以下方法:
$(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! 这只是个人风格的问题!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.