javascriptprocessing.js

ProcessingJS Create an Object which holds random number of items to draw flowers


I am working on drawing a tulip flower in ProcessingJS. I have code as below. The code will draw a tulip flower with a petal, and x, y, height is the preference for pedal location and height.

`/*****************
*Tulip Object Type
******************/
var Tulip = function(x, y, height) {
    this.x = x;
    this.y = y;
    this.height = height;
};

Tulip.prototype.draw = function() {
    noStroke();
    fill(16, 122, 12);
    rect(this.x, this.y, 10, -this.height);
    fill(255, 0, 0);
    // petals
    ellipse(this.x+5, this.y-this.height, 44, 44);
    triangle(this.x-16, this.y-this.height,
            this.x+20, this.y-this.height,
            this.x-20, this.y-this.height-31);
    triangle(this.x-14, this.y-this.height,
            this.x+24, this.y-this.height,
            this.x+3, this.y-this.height-39);
    triangle(this.x+-4, this.y-this.height,
            this.x+26, this.y-this.height,
            this.x+29, this.y-this.height-36);
};
`

Function to draw:

void setup()
{
  size(400 , 400);
  background(125);
}

 var tulip = new Tulip (200, 200, 10);
 draw = function() {
    tulip.draw();

};

I want to draw random numbers of tulip flowers, with the value of x, y and height also randomly set respectively.

I'm thinking of using an array but after many tries still not working. How I create randomly flowers based on the Tulip object above?


Solution

  • Create an array of random tulips:

    int numTulips = random(10, 20); // between 10 and 20 tulips
    Tulip[] tulips = new Tulip[numTulips];
    for (int i = 0; i < numTulips; i++) {
      tulips[i] = new Tulip (random(30, 370), random(30, 370), random(10, 30));
    }
    

    Then draw the tulips

    draw = function() {
       for (int i = 0; i < numTulips; i++) {
          tulips[i].draw();
        }
     };
    

    Sample: https://codepen.io/bortao/pen/jOPobam