Position relative to shape

Hi!

Beginner question: is it possible to position elements relative to another shape. For example lets say I want to place 9 rectangles into another rectangle, it would be great if the size and position of the child rectangles could be derived from the parent rectangle. I know I can do this myself with variables, but it gets messy at some point.

Thanks!

1 Like

Hello @casperleerink,

It sure is possible and in more than one way. :blush: You can dream up your own function that does what you want precisely. Or skim through the p5.js Reference, keeping an eye out for anything that looks interesting.

With your question in mind, translate() and scale() stood out to me. Here’s an example of how they can work together:

const PARENT_SQUARE_SIZE = 100;

function setup() {
  createCanvas(400, 400);
  
  background(220);

  rectMode(CENTER);
  translate(width / 2, height / 2);

  square(0, 0, PARENT_SQUARE_SIZE);
  scale(0.5);
  square(0, 0, PARENT_SQUARE_SIZE);
  
  noLoop();
}

2 Likes