如何在一个数组中一个一个地绘制一个对象而不是同时全部?

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

我将 p5js 库与 JavaScript 一起使用,并且正在制作一个程序来显示随机颜色和位置的斑点。唯一的问题是所有的斑点都是在 for 循环中创建的,然后一次绘制。我该怎么做才能一次绘制一个点,然后停在数组的末尾?我使用的全部代码如下:

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)
  }
}

你可以这样做。

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();

如果您不希望所有点都出现在开始处,则不应在 setup 函数中创建它们。而是每次调用 draw 时都创建一个点,直到没有更多点可创建为止。由于 draw 被 p5 库异步调用,您会看到它们逐渐出现。

因此您需要进行两项更改,在下面的代码段中用注释标记:

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>