Create a grid out of rectangles

Hi, I want to draw rectangles (size=50) in a grid of 7 columns and 6 rows. With a sketch border offset of 15
pixels and 5 pixels between each rectangle. This is how it should look like: Screenshot_1 . When I try add the space somewhere between, rectangles are starting to missalign and I’m also not sure how to replicate it on Y axis alone as when I try to do that, rectangles are replicated diagonally.

Here’s what I have so far:

int rectSize=50;
int space=5;
int xPos=15, yPos=15;

void setup() {
  size(500, 500);
  background(255);
  frameRate(10);
}

void draw() {
  rect(xPos, yPos, rectSize, rectSize);
  xPos=xPos+rectSize;
  xPos%=(width-rectSize);
}
1 Like

Maybe these 2 online sketches which create a grid of rect() can help you figure it out: :innocent:

  1. Studio.ProcessingTogether.com/sp/pad/export/ro.9L5jAtga7SpyF
  2. Studio.ProcessingTogether.com/sp/pad/export/ro.9ABG0RKl9D2Bx
1 Like

Thats too complex, I can only use basic functions.

Just use some basic ideas from there. Like defining constants for GRID, SIZE, MARGIN, SPACE, etc. :sunglasses:
And the double loops for rect() too. :nerd_face:

Hi Jerkz,

I’m not sure the draw loop is the best place to do what you want. Instead, simply use for loops inside the setup.

Here a small example that draw a 3*3 matrix:

int rectSize=90;
int space=10;

void setup() {
  size(310, 310);
  background(20);
  stroke(200);
  noFill();
  strokeWeight(2);

  for (int x = 0; x < 3; x++) {
    for (int y = 0; y < 3; y++) {
      rect(space + x * (rectSize + space), space + y *(rectSize + space), rectSize, rectSize);
    }
  }
}
  • x correspond to the column you are dealing with
  • y correspond to the row you are dealing with
  • To know the position of a square based on the column on row, you just need to add up all the space taken by previous square on the left and on the top. This is handle by this:
    • space + x * (rectSize + space)
    • space + y *(rectSize + space)
2 Likes