Drawing a flower

Hello!

I’ve drawn a mathematical rose and I can’t think of a way of animating it so it will slowly draw the line out.
It will just print out the whole rose at once. How can I make it so it will draw out the lines like a pencil drawing it out on paper?

float LENS = 2;
float RATE = 8;
float k = RATE / LENS;
  
void setup() {
  size(500, 500);
}

void draw() {
  background(0);
  stroke(#FFFFFF);
  noFill();
  strokeWeight(1);
  drawRose();
}
  
  void drawRose(){
    beginShape();
    translate(width / 2, height / 2);
    for (float t = 0; t < TWO_PI * LENS; t += 0.02) {
    float r = 200 * cos(k * t);
    float x = r * cos(t);
    float y = r * sin(t);
    vertex(x, y);

  }
  endShape(CLOSE);
}
2 Likes

Great question!

I suggest taking a look at PShape.getVertexCount() and PShape.getVertex().

Also, I suggest having drawRose() return a PShape object - currently all the drawing happens all at once because you’re calling drawRose() every frame.

What you’ll want to do is only draw a few vertices every frame, and keep a track of how many you’ve already drawn with some sort of time constant like a count variable that gets incremented every frame.

1 Like

Also consider using interpolation – lerp() and/or PVector.lerp().

So, rather than drawing a line as a sequence of many points, draw a line that is between 0 and 100% between two end points.

int begin = 10;
int end = 90;
void draw(){
  background(192);
  float progress = (millis()%2000)/2000.0;    // clock
  float endNow = lerp(begin, end, progress);  // calculate position
  line(begin, begin, endNow, endNow);         // display
}

This technique can be used on arcs, curves, etc – or to slide the index on how many points in a multi-part curve to display.

Edit:

To give a concrete example of applying a simple timer as above to a for loop (even without lerp), watch what happens to your flower when you update a global timer variable at the top of draw:

void draw(){
  progress = (millis()%2000)/2000.0;

…and then use that to timer to decide how much of your flower to draw in the for loop:

for (float t = 0; t < TWO_PI * progress; t += 0.02) {

(you may no longer want to use CLOSE in endShape()).

As a side note, you can also stop drawing once the number of cycles reaches a whole number when the angle is a multiple of TWO_PI. On even k values, this may be twice the actual value, so I’m sure there’s a better way of doing this.