0
2 차원 캔버스 애니메이션을 배우려고하지만 이미 생성 된 애니메이션을 유지하는 방법을 알 수 없습니다.캔버스 지우기 이미 실행중인 애니메이션 저장
예 : 클릭 할 때 화면의 왼쪽 상단으로 실행되는 원을 만들지 만 다시 클릭하면 애니메이션이 지워지고 새 애니메이션이 시작됩니다. 한 번에 두 개 이상의 서클을 실행하고 싶습니다.
코드 :
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);
});
}