How do I draw an object in an array one by one not all at the same time?

166 views Asked by At

I am using the p5js libraries with JavaScript and am making a program to display spots of random colour and position. The only thing is that all the spots are made in the for loop and are then drawn all at once. How do I make it so the spots are drawn one at a time, but then stop at the end of the array? The whole code i am using is below:

var spots = []
var ammount = 1000

function setup() {
  createCanvas(windowWidth , windowHeight);
  background(0);
  for (var i = 0; i <= ammount; i++) {
    spots[i] = new Spot();
  }
}

function draw() {
  for (var i = 0; i < spots.length; i++) {
    spots[i].render();
  }
}

function Spot() {
  this.x = random(0, width);
  this.y = random(0, height);
  this.d = 24
  this.col = {
    r:random(50, 200),
    g:random(20, 241),
    b:random(100, 200),
    alpha: random(50, 150)
  };

  this.render = function() {
    noStroke();
    fill(this.col.r,this.col.g,this.col.b,this.col.alpha);
    ellipse(this.x, this.y, this.d, this.d)
  }
}
2

There are 2 answers

1
trincot On BEST ANSWER

If you don't want all spots to appear at the start, then you should not create them in the setup function. Instead create one spot every time draw is called, until you have no more spots to create. As draw is called asynchronously by the p5 library, you'll see them appear gradually.

So you need to make two changes, marked in the below snippet with a comment:

var spots = []
var ammount = 1000

function setup() {
  createCanvas(windowWidth , windowHeight);
  background(0);
  // don't create the spots at the setup phase
}

function draw() {
  for (var i = 0; i < spots.length; i++) {
    spots[i].render();
  }
  // As long as you have not created all spots, create one now:
  if (spots.length < ammount) spots.push(new Spot());
}

function Spot() {
  this.x = random(0, width);
  this.y = random(0, height);
  this.d = 24
  this.col = {
    r:random(50, 200),
    g:random(20, 241),
    b:random(100, 200),
    alpha: random(50, 150)
  };

  this.render = function() {
    noStroke();
    fill(this.col.r,this.col.g,this.col.b,this.col.alpha);
    ellipse(this.x, this.y, this.d, this.d)
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.5/p5.min.js"></script>

0
Lalith Prasad On

You could do something like this.

var i = 0;
var iterationCount = spots.length;
function draw () {
    spots[i].render();
    i++;
    if (i <= iterationCount){
        setTimeout(draw, 500); // Here 500 will be equivalent to half a second. so you will have a spot for every half a second
    }
}
draw();