2013-06-20 115 views
0

我正在嘗試使用HTML5和畫布創建浮動效果。我可以在https://layervault.com/上看到我要做的一個示例您可以通過滑動條前往第4張幻燈片(標題爲「iOS的LayerVault簡介」)來查看示例。在那張幻燈片上,很多圓圈都浮出了對象。到目前爲止,在我的代碼中,我只能得到1個圓圈浮起來。關於我應該採取的方法的任何想法?HTML5畫布浮動圈

我迄今爲止代碼:

$(document).ready(function() { 
var canvas = $("#myCanvas").get(0); 
var context = canvas.getContext("2d"); 

var circleColors = new Array(); 
circleColors[0]="#f0f"; 
circleColors[1]="#0f0"; 
circleColors[2]="#00f"; 
circleColors[3]="#f00"; 

function makeCircles() { 
    var posX = Math.floor(Math.random()*500); 
    var posY = 500; 
    var theCircleColor = circleColors[Math.floor(Math.random()*circleColors.length)]; 

    function renderContent() 
    { 
     context.save(); 
     context.fillStyle=theCircleColor; 
     context.beginPath(); 
     context.arc(posX,posY,40,0,2*Math.PI); 
     context.fill(); 
     context.restore(); 
    }//end function renderContent 

    function animationLoop() 
    { 
     canvas.width = canvas.width; 
     renderContent(); 
     posY -= 5; 
     if (posY < -40) 
      posY = 500; 
     setTimeout(animationLoop, 33); 
    }//end function animationLoop 


    animationLoop(); 
}//end function makeCircles 

    makeCircles(); 

});//end document ready 

回答

2

你需要做圓的陣列,每圈都需要自己的X/Y /顏色和潛在的速度,所以他們以不同的速度移動。

所以每圈將與

{ 
    posX: someValue, 
    posY: someValue, 
    color: someValue, 
    speed: someValue 
}; 

然後一個JavaScript對象,我們將增加許多那些陣列。下面是一個例子使用代碼:

var canvas = $("#myCanvas").get(0); 
var context = canvas.getContext("2d"); 

var circleColors = new Array(); 
circleColors[0] = "#f0f"; 
circleColors[1] = "#0f0"; 
circleColors[2] = "#00f"; 
circleColors[3] = "#f00"; 

var circles = []; 

function makeCircles() { 
    for (var i = 0; i < 20; i++) { 
     var circle = { 
      posX: Math.floor(Math.random() * 500), 
      posY: 500, 
      color: circleColors[Math.floor(Math.random() * circleColors.length)], 
      speed: Math.floor(Math.random()*5) 
     }; 
     circles.push(circle); 
    } 

    function renderContent() { 
     for (var i = 0; i < circles.length; i++) { 
      var c = circles[i]; 
      context.fillStyle = c.color; 
      context.beginPath(); 
      context.arc(c.posX, c.posY, 40, 0, 2 * Math.PI); 
      context.fill(); 
     } 
    } //end function renderContent 

    function animationLoop() { 
     canvas.width = canvas.width; 
     renderContent(); 
     for (var i = 0; i < circles.length; i++) { 
      var c = circles[i]; 
      c.posY -= c.speed; 
      if (c.posY < -40) c.posY = 500; 
     } 
     setTimeout(animationLoop, 33); 
    } //end function animationLoop 


    animationLoop(); 
} //end function makeCircles 

makeCircles(); 

這裏,它是活的:

http://jsfiddle.net/vTaLF/

+0

+1,尼斯的工作一如既往! :)也許也使用requestAnimationFrame? – markE