Sad Hyena
Sad Hyena

Reputation: 311

How to draw a star in P5.js?

I'm trying to make a class "star" with a method inside of it that, at given coordinates and size, draws a star. Something like rect() or ellipse() functions.

How can make it?

Upvotes: 2

Views: 5144

Answers (3)

Jasper
Jasper

Reputation: 631

Old question, but still relevant.

The below function works well for me. It takes a value for the xy location, the number of points you want the star to have and the inner radius (center to valley) and outer radius (center to point).

It basically works the same as when you try to draw a circle manually by drawing a sequence of points revolving around a center position, but by switching between the inner and outer radius for every point, you end up with a star shape.

function star(x, y, num_points, inner_radius, outer_radius) {
  const angle = TWO_PI / num_points; // angle between two points
  const halfAngle = angle / 2.0; // angle between point and valley
  
  beginShape();
  for (let a = 0; a < TWO_PI; a += angle) {

    let sx = x + cos(a) * outer_radius;
    let sy = y + sin(a) * outer_radius;
    vertex(sx, sy); // vertex at point of star

    sx = x + cos(a + halfAngle) * inner_radius;
    sy = y + sin(a + halfAngle) * inner_radius;
    vertex(sx, sy); // vertex at valley

  }
  endShape(CLOSE);
}

Image showing how the parameters relate to the final star shape

Upvotes: 1

Sussy baka
Sussy baka

Reputation: 1

With the new update on p5 you can simply type star(coordinates) and then make the star.

Upvotes: -2

Kevin Workman
Kevin Workman

Reputation: 42174

The best advice I can give you is to get out a piece of paper and a pencil. Draw out the points of a star, and label their X and Y coordinates.

Then you can use something like the line() or beginShape() function to draw that on the screen using code.

You can find more info in the P5.js reference.

Upvotes: 2

Related Questions