如何解决P5.JS使用For循环绘制rect的居中集合
我正在尝试以3x2的方式(如下所示)创建类似网格的结构,但我希望将其居中放置在画布上,并使其根据width
和{ {1}}。我希望不使用height
或scale();
函数,并且如果可能的话,最好都与我当前的代码相似。我试图用不同的数学来抵消和弄乱,但我似乎无法理解。我目前的尝试是这样的; Attempt
这是我的代码;
resizeCanvas;
解决方法
因此,在尝试您的代码时,实际上得到的结果与问题中链接的图像不同,但这没关系。
不会改变结果但有更好实践的一些事情:
1-如果从不更改变量的范围,则最好声明为const
而不是let
。
2-将rectMode()
和fill()
放在draw()
中,即使它们的参数从不改变也没有用,最好在setup()
中使用它们。
3-我将background()
留在了draw()
内,因为它在您要移动矩形(或做其他任何图形)而又看不到到目前为止绘制的所有图形的轨迹的情况下很有用。>
现在让我们来看一下我找到的解决方案:
第一个,不调用rectMode()
,因此默认情况下从角落开始绘制矩形,如图所示,较少的计算要做:
function setup()
{
createCanvas(500,500);
fill(255,0);
}
function draw()
{
background(100);
//Set the space between the edge of the canvas and your rectangles.
const offsetX = width/10;
const offsetY = width/10;
/*
Set the size of the rectangles so that they are X times smaller the width
(or height) of the canvas already reduced of the space from the edges,where X is the number of rectangles that make up the rows (or columns).
*/
const sizeX = (width-offsetX*2)/3;
const sizeY = (height-offsetY*2)/2;
for(let i = 0; i < 3; i++)
{
for(let j = 0; j < 2; j++)
{
rect(i*sizeX +offsetX,j*sizeY +offsetY,sizeX,sizeY);
}
}
}
第二个,设置rectMode(CENTER)
。它需要更多的计算和rectMode()
的调用,但除此以外,它并没有太大变化(注释是相同的,因此我不再重复):
function setup()
{
createCanvas(500,500);
rectMode(CENTER);
fill(255,0);
}
function draw()
{
background(100);
const offsetX = width/10;
const offsetY = width/10;
const sizeX = (width-offsetX*2)/3;
const sizeY = (height-offsetY*2)/2;
for(let i = 0; i < 3; i++)
{
for(let j = 0; j < 2; j++)
{
/*
Add also half of the size so that the offset is from the edge of the
rectangle and not from the center.
*/
rect(i*sizeX+offsetX+sizeX/2,j*sizeY+offsetY+sizeY/2,sizeY);
}
}
}
我希望这就是您要的,如果您有任何疑问,请不要犹豫。
编辑
在绘制矩形时添加了颜色更改(在评论中要求):
const colors = ['red','green','blue'];
function setup()
{
createCanvas(500,500);
}
function draw()
{
background(100);
const offsetX = width/10;
const offsetY = width/10;
const sizeX = (width-offsetX*2)/3;
const sizeY = (height-offsetY*2)/3;
for(let i = 0; i < 3; i++)
{
for(let j = 0; j < 2; j++)
{
fill(colors[i]);
rect(i*sizeX +offsetX,sizeY);
}
}
}
让我知道这是否是您想要的。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。