2013-09-27 2 views
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); 
    }); 
} 

답변

0

나는 캔버스의 삭제가 문제라고 생각하지 않습니다.

는 내가 접근 할 방법 :

가 대신 변수의 객체로 circle를 확인합니다.

이제 새 서클 개체를 만들고 캔버스와 서클 목록에 추가하는 새 기능 addCircle()을 만드십시오. 여기에서 drawCircle() 함수를 사용할 수 있습니다.

animate() 함수를 수정하여 새로운 서클 목록을 반복함으로써 각 서클을 이동합니다.

최소한 궤적을 유지해야합니다.