2016-12-16 52 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(); 
相關問題