我正在使用带有JavaScript的p5js库,我正在制作一个程序来显示随机颜色和位置的斑点。唯一的事情是所有的斑点都是在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)
}
}
答案 0 :(得分:0)
你可以这样做。
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();
答案 1 :(得分:0)
如果您不想在开始时显示所有位置,则不应在设置功能中创建它们。而是每次调用 draw 时创建一个点,直到你没有更多的点可以创建。由于p5库异步调用 draw ,你会看到它们逐渐出现。
因此,您需要进行两项更改,并在下面的代码段中标注注释:
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>