2016-08-21 17 views
0

キャンバス要素を使用して、黒いキャンバスの背景に白い四角形を描きます。キャンバス上に四角形を描画すると、1つの四角形しか描画されない

私は黒い背景を描くのに苦労せず、1つの星を描くことができますが、複数の白い四角を描くのが難しいです。しかし、私は各ループに新しい白い星を描いているので、混乱しています。何らかの理由で、各星を描いていない(白い四角形)。

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()への呼び出しを移動しました。あなたのコードはただ1つの場所を選んでいて、同じ場所(互いの上にある)にすべての星を描いていました。各星に別のランダムな場所が必要です。

+0

もちろん!同じ位置に同じ星を描いていたのは理にかなっている!私はできるときにあなたに緑のマークを与えるだろう!ありがとう! –

関連する問題