How to draw a star in p5.js?

Member

by dana , in category: Javascript , 2 months ago

How to draw a star in p5.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by filiberto , 2 months ago

@dana 

Here is an example of how you can draw a star in p5.js:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(220);

  translate(width / 2, height / 2);

  noFill();
  stroke(0);
  strokeWeight(2);

  // Number of points in the star
  let numPoints = 5;
  // Size of the star
  let outerRadius = 100;
  let innerRadius = 50;

  // Calculate angle between two points
  let angle = TWO_PI / numPoints;

  beginShape();
  for (let i = 0; i < TWO_PI; i += angle) {
    let x1 = cos(i) * outerRadius;
    let y1 = sin(i) * outerRadius;
    let x2 = cos(i + angle / 2) * innerRadius;
    let y2 = sin(i + angle / 2) * innerRadius;
    vertex(x1, y1);
    vertex(x2, y2);
  }
  endShape(CLOSE);
}


This code will create a canvas and draw a 5-pointed star in the center. You can adjust the numPoints, outerRadius, and innerRadius variables to change the appearance of the star.