2014-09-25 64 views
0

我想知道是否有可能在一個不復雜的方式使這個循環?For循環一個畫布動畫

我正在使用9種不同顏色的代碼...... for-loop會縮短我的代碼量。我對JS很新穎,我不能真正想到一種簡單的方式。唯一改變的是「紅色」到「綠色」或「黃色」等等。 顏色名稱是唯一的變化,'x'和'y'座標爲

} else if (collides(myRectRed, x, y)) { 
     context.fillStyle = "White"; 
     context.fillRect(107, 7, 90, 110); 

     function callbackRed() { 
      setTimeout(function returnSizeRed() { 
       context.fillStyle = "Red"; 
       context.fillRect(107, 7, 90, 110); 
      },50); 
     } 
     function callMIDRed(){ 
      setTimeout(function displayMidRed(){ 
       context.fillStyle = "Red"; 
       context.fillRect(119, 22, 60, 80); 
       return callbackRed(); 
      },50); 
     } 
     setTimeout(function displayRectRed() { 
      context.fillStyle = "Red"; 
      context.fillRect(139, 42, 20, 40); 
      return callMIDRed(); 
     },50); 
+0

你會想看看* *關閉,然後你可以輕鬆使用循環。 – Bergi 2014-09-25 15:52:03

回答

1

只保留對象數組中的重要信息。一個對象可以包含顏色, x, y。假設你有3個這樣的對象在數組中。

然後,每次該函數調用,您可以通過一個incremeant我,如果達到3%你是把它帶回0,一次又一次......

當你運行的功能,你只要從這個數組中獲取信息。

var s = [ 
{color: "Red", x: 120, y:120}, 
{color: "Green", x: 160, y:120}, 
{color: "Blue", x: 200, y:120}, 
]; 

var i = 0; 

var changeColors = function() { 
    context.fillStyle = s[i].color; 
    context.fillRect(s[i].x, s[i].y, 10, 10); 
    i = i++ % 3; 
} 

而現在,只需設定時間間隔該功能(切記不要在函數名放在()在的setInterval功能)

var interval = setInterval(changeColors, 1000); 

或者停止它

clearInterval(interval); 
+0

這隻適用於如果我改變畫布1次,我期待用3個setTimeout函數更改我的畫布。這不是我的解決方案。但我確實發現將所有相關信息放入一個數組很有用:)感謝您的回覆。 – 2014-09-29 17:56:48

0

你確定你需要3個超時功能嗎?

function first() { 
    // something 
    setTimeout(first, 50); 
} 
function second() { 
    // something 
    setTimeout(second, 50); 
} 
function third() { 
    // something 
    setTimeout(third, 50); 
} 

也許改變以前的這種

function first() { 
    // something 
} 
function second() { 
    // something 
} 
function third() { 
    // something 
} 

function invoke() { 
    first(); 
    second(); 
    third(); 
    setTimeout(invoke, 50); 
} 

但我不知道,做你想做的:d