How to draw rectangles inside a polygon using p5.js?

by giovanny.lueilwitz , in category: Javascript , 11 days ago

How to draw rectangles inside a polygon using p5.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by gilbert , 11 days ago

@giovanny.lueilwitz 

To draw rectangles inside a polygon using p5.js, you can follow these steps:

  1. First, create a canvas using the createCanvas() function and set the size of the canvas.
  2. Define the points that make up the vertices of the polygon using the beginShape() and vertex() functions.
  3. Use the endShape(CLOSE) function to close the polygon.
  4. Inside the draw() function, use the rect() function to draw rectangles inside the polygon. You can set the position and size of the rectangles based on the vertices of the polygon.


Here is an example code snippet that shows how to draw rectangles inside a polygon using p5.js:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(220);
  
  beginShape();
  vertex(100, 100);
  vertex(200, 100);
  vertex(200, 200);
  vertex(100, 200);
  endShape(CLOSE);
  
  rect(120, 120, 40, 40); // Draw a rectangle inside the polygon
  rect(160, 160, 40, 40); // Draw another rectangle inside the polygon
}


This code will create a canvas with a polygon shape and draw two rectangles inside the polygon. You can modify the position and size of the rectangles to fit your desired layout.