2016-12-16 34 views
0

我在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

如果你不希望所有的斑点出现在一开始,那么你不应该在设置函数来创建它们。相反,每次创建一个点绘制被调用,直到你没有更多的点创建。 As 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>

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