How to draw squares between an array of points in p5.js?

Member

by rollin , in category: Javascript , 6 months ago

How to draw squares between an array of points in p5.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by scotty_walker , 6 months ago

@rollin 

To draw squares between an array of points in p5.js, you can use the rect() function to draw a square for each pair of adjacent points in the array. Here's an example code snippet that demonstrates this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
let points = [
  { x: 100, y: 100 },
  { x: 200, y: 100 },
  { x: 200, y: 200 },
  { x: 100, y: 200 }
];

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

function draw() {
  background(220);

  // Draw squares between each pair of adjacent points
  for (let i = 0; i < points.length; i++) {
    let p1 = points[i];
    let p2 = points[(i + 1) % points.length];
    rect(p1.x, p1.y, p2.x - p1.x, p2.y - p1.y);
  }
}


In this code, we first define an array of points representing the corners of a square. Inside the draw() function, we loop through each pair of adjacent points in the array and use the rect() function to draw a square between them. The p5.js library will automatically connect the last and the first point to form a closed shape.

Related Threads:

How to draw a star in p5.js?
How does the p5.js draw function work?
How to draw in polar coordinates with p5.js?
How to draw only segment of whole image with p5.js?
How to use csv data and draw in p5.js?
How to draw a line in p5.js using webgl?