P5.JS 使用 For 循环绘制一组居中的矩形

P5.JS Using a For loop to draw a centred set of rect's

我正在尝试创建一个 3x2 样式的网格状结构,如下所示,但我希望将它以 canvas 为中心,并让它根据 widthheight。我希望在不使用 scale();resizeCanvas; 函数的情况下这样做,并且如果可能的话,理想情况下这样做与我当前的代码类似。我试过抵消和搞乱不同的数学,但我似乎无法理解。我目前的尝试是这样的; Attempt 这是我的代码;

function setup() {
    createCanvas(500, 500);
}

function draw() {
    background(100);
    rectMode(CENTER);

    let posX = width * 0.5;
    let posY = height * 0.5;
    let sizeX = width / 3;
    let sizeY = height / 3;

    for (let i = 0; i < 3; i++) {
        for (let j = 0; j < 2; j++) {
            fill('Red');
            rect(i * posX + 75, j * posY + 75, sizeX - 50, sizeY - 50);
        }
    }
}

因此,在尝试您的代码时,我实际上得到了与您问题中链接的图片不同的结果,但这并不重要。
一些不会改变结果但更适合实践的事情:
1 - 如果您从不在变量范围内更改变量的值,最好将其声明为 const 而不是 let.
2 - rectMode()fill()draw() 中,即使它们的参数永远不会改变也是无用的,最好在 setup().
中使用它们 3 - 我将 background() 留在了 draw() 中,因为如果你想移动矩形(或做任何其他绘图)而不看到目前为止所有绘图的轨迹,它会很有用。

现在让我们来看看我找到的解决方案:
第一个,不调用 rectMode() 以便默认从角绘制矩形,如图所示,需要做的计算较少:

function setup()
{
    createCanvas(500, 500);
    fill(255, 0, 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, 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, sizeX, 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, j*sizeY +offsetY, sizeX, sizeY);
        }
    }
}

如果这是你想要的,请告诉我。