2016-12-16 2 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

모든 지점은 시작에 표시하지 않는 경우, 당신은 설정 함수를 만들면 안됩니다. 대신 더 이상 생성 할 자리가 없을 때까지 드로잉이 호출 될 때마다 하나의 스폿을 만듭니다. 드로잉은 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(); 
관련 문제