2013-09-27 97 views
0

我想學習2D畫布動畫,但無法弄清楚如何保持動畫已經創建運行。清除畫布保存已經運行的動畫

例如:點擊我創建一個運行到屏幕左上角的圓,但是當我再次單擊時,該動畫被清除並且一個新的啓動。我想要一次運行多個圈子。

代碼:

window.requestAnimFrame=(function(callback){ 
    return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(callback){ 
     window.setTimeout(callback,1000/60); 
    }; 
})(); 

var can = $('canvas')[0], 
    ctx = can.getContext('2d'), 
    width = window.innerWidth, 
    height = window.innerHeight-5, 
    color = ''; 

can.width = width; 
can.height = height; 
can.addEventListener('click',randomColor); 
can.addEventListener('click',animate); 

var circle = { 
    x:0, 
    y:0, 
    r:5, 
    d:2*Math.PI, 
    color:'' 
} 

function drawCircle(){ 
    ctx.beginPath(); 
    ctx.arc(circle.x,circle.y,circle.r,0,circle.d,false); 
    ctx.fillStyle = circle.color; 
    ctx.fill(); 
} 

function randomColor(){ 
    color = 'rgba('+Math.floor(Math.random()*255)+','+Math.floor(Math.random()*255)+','+Math.floor(Math.random()*255)+',1)'; 
} 

function clear(){ 
    ctx.clearRect(0,0,can.width,can.height); 
} 

function animate(event,startTime){ 
    if(startTime==undefined){ 
     startTime = (new Date()).getTime(); 
    } 
    circle.x = event.clientX; 
    circle.y = event.clientY; 
    circle.color = color; 
    var time = (new Date()).getTime()-startTime; 
    var speed = (300*time/1000); 
    circle.x += speed; 
    circle.y -= speed; 
    if (circle.x+circle.r>width||circle.y<0||circle.y>height||circle.x<0) { 
     return; 
    } 
    clear(); 
    drawCircle(); 
    requestAnimFrame(function(){ 
     animate(event,startTime); 
    }); 
} 

回答

0

我不認爲畫布的結算就是問題所在。

我怎麼會來解決:

circle成一個對象,而不是一個變量。

現在創建一個新函數addCircle()它創建一個新的圓形對象,並將其添加到您的畫布和圓形列表(您可以在這裏使用您的drawCircle()函數)。

修改您的animate()函數,以便遍歷新的圓形列表,從而移動每個圓形。

這應該至少讓你走上正軌。