我正在尝试学习 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);
});
}