2016-08-21 5 views
0

캔버스 요소를 사용하여 검은 캔버스 배경에 흰색 사각형을 그립니다.불투명 한 루프의 캔버스에 사각형 그리기 하나의 사각형 만 그리기

검은 색 배경을 그리는 데 어려움이없고 한 개의 별을 그릴 수 있지만 두 개 이상의 흰색 사각형을 그리는 데 어려움이 있습니다. 그러나 각 루프마다 새로운 흰색 별을 그리는 중 혼란 스럽습니다. 어떤 이유로 각 별 (흰색 사각형)을 그리지 않습니다. 아래

Based on this article I believe my code should work.

참조하십시오 코드 :

function Starfield() { 
    this.ctx = document.getElementById('canvas'); 
    this.ctx = this.ctx.getContext("2d"); 
    this.stars = 2; 
    this.createCanvas(); 
    this.createStar(); 
} 

Starfield.prototype.createCanvas = function() { 
    this.ctx.fillStyle = "#000"; 
    this.ctx.fillRect(0,0, window.innerHeight, window.innerWidth); 
}; 

Starfield.prototype.createStar = function() { 
    var rand1 = Math.random() * 50; 
    var rand2 = Math.random() * 50; 
    for (var i = 0; i < this.stars; i++) { 
     this.ctx.fillStyle = "#fff"; 
     this.ctx.fillRect(rand1, rand2, 2, 2); 
    }; 
}; 

답변

4

는 아래의 시도는 :

Starfield.prototype.createStar = function() { 
    for (var i = 0; i < this.stars; i++) { 
     var rand1 = Math.random() * 50; 
     var rand2 = Math.random() * 50; 
     this.ctx.fillStyle = "#fff"; 
     this.ctx.fillRect(rand1, rand2, 2, 2); 
    }; 
}; 

나는 루프 내부 Math.random()에 전화를 옮겼습니다. 귀하의 코드는 단지 하나의 위치를 ​​선택하고 동일한 위치 (서로 위에)에있는 모든 별을 그렸습니다. 각 별마다 다른 임의의 위치가 필요합니다.

+0

물론! 같은 위치에 같은 별을 그리는 것이 합리적입니다. 내가 할 수 있으면 녹색 마크를 줄거야! 감사! –