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);
});
}