如何移动一些用循环函数制作的矩形

How to move some rectangles made with the Loop function

如何移动这 6 个矩形。 我想我必须为循环更改 X 和 Y,但我不知道如何更改。我会喜欢一些帮助。

这是代码:https://editor.p5js.org/AlexArek/sketches/r1eVquBkV

let cols = 3;
let rows = 3;


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

function draw() {
  background(90, 140, 210);

  for (let i = 0; i < cols; i++) {
    for (let j = 0; j < rows; j++) {
      let x = i * 110;
      let y = j * 110;
      noFill()
      rect(x, y, 100, 100)
    }
  }
//How can I move this whole thing in the middle of the screen?
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/p5.js"></script>

首先你必须计算你的对象的框(宽度和高度):

let obj_w = 110 * (cols-1) + 100;
let obj_h = 110 * (rows-1) + 100;

然后你必须将对象的中心移动到 canvas 的中心translate()

内置变量 width and height 包含 canvas 的大小。 如果您移动 canvas 大小的一半,则对象的左上角将位于 canvas:

的中心
translate(width/2, height/2);

如果你向相反的方向直接移动物体的一半大小,那么物体的中心就在canvas的中心:

translate(-obj_w/2, -obj_h/2);

let cols = 3;
let rows = 3;

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

function draw() {
  background(90, 140, 210);

  let obj_w = 110 * (cols-1) + 100;
  let obj_h = 110 * (rows-1) + 100;
  translate(width/2, height/2);
  translate(-obj_w/2, -obj_h/2);

  for (let i = 0; i < cols; i++) {
    for (let j = 0; j < rows; j++) {
      let x = i * 110;
      let y = j * 110;
      noFill()
      rect(x, y, 100, 100)
    }
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/p5.js"></script>