2013-09-24 51 views
1

我正在學習使用畫布進行JavaScript學習的過程,我設法使用隨機生成的顏色製作正方形網格。爲什麼我的畫布空白,除了在角落?

我決定讓每個正方形顏色的強度增加和減少,但結果只是被繪製的網格的一個小角落,並且顏色不會改變。我究竟做錯了什麼?

Online code herepaste bin here

var canvas = document.getElementById('myCanvas'); 
var ctx = canvas.getContext("2d"); 

ctx.clearRect(0, 0, canvas.width, canvas.height); 

function square(x, y) { 
    this.x = x; 
    this.y = y; 
    this.sizex = 10; 
    this.sizey = 10; 
    this.Colo = Colo; 

    function Colo() { 
     var r = Math.floor(Math.random() * (255 - 1) + 1); 
     var g = Math.floor(Math.random() * (255 - 1) + 1); 
     var b = Math.floor(Math.random() * (255 - 1) + 1); 
     var run = true; 
     var rup, gup, bup = true; 
     while (run) { 

      if (rup) { 
       if (r == 255) { 
        rup = false; 
       } else if (r == 0) { 
        rup = true; 
       } 

       r += 1; 
       r.toString(); 

      } else if (!gup) { 
       r -= 1; 
       r.toString(); 
      } 

      if (gup) { 
       if (g == 255) { 
        gup = false; 
       } else if (g == 0) { 
        gup = true; 
       } 
       g += 1; 
       g.toString(); 

      } else if (!gup) { 
       g -= 1; 
       g.toString(); 
      } 

      if (bup = true) { 
       if (b == 255) { 
        bup = false; 
       } else if (b == 0) { 
        bup = true; 
       } 

       b += 1; 
       b.toString(); 

      } else if (!gup) { 
       b -= 1; 
       b.toString(); 
      } 

      ctx.clearRect(0, 0, canvas.width, canvas.height); 
      var col = "rgb(" + r + "," + g + "," + b + ")"; 

      return col; 
      window.onfocus = function() { 
       rup = true; 
      }; 
      window.onblur = function() { 
       isActive = false; 
      }; 
      console.log("Ran loop.") 
     } 
    } 

    ctx.fillStyle = Colo(); 
    ctx.fillRect(this.x, this.y, this.sizex, this.sizey); 
} 

var squares = new Array(); 
var p = 0; 
for (var i = 0; i < 128; i++) { 
    for (var j = 0; j < 72; j++) { 
     p = i + j; 
     squares[p] = new square(i * 10, j * 10); 
    } 
} 

回答

3

square()構造做到這一點:

ctx.fillStyle = Colo(); 
ctx.fillRect(this.x, this.y, this.sizex, this.sizey); 

...其中Colo(),除其他事項外,這是否:

ctx.clearRect(0, 0, canvas.width, canvas.height); 

所以,你清除油漆前,然後整個畫布每個矩形。

+0

感謝您的幫助!對不起,謝謝。 – user2751351