2016-08-21 139 views
0

我使用畫布元素在黑色畫布背景上繪製白色正方形。在foor loop的畫布上繪製正方形只繪製一個正方形

我沒有困難畫一個黑色的背景,並可以繪製一顆星,但是我有困難繪製多個白色方塊。我很困惑,因爲我在每個循環中繪製一個新的白色星星,但由於某種原因,它並沒有畫出每顆星星(白色方塊)。

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

當然!有道理,在相同的位置上繪製了同樣的明星!當我可以的時候會給你綠色標記!謝謝! –