2013-12-21 3 views
0

원이 내 캔버스 주위를 움직이기를 원합니다.html5 애니메이션 : 캔버스 지우기 woks하지만 모든 것이 다시 그려집니다

그래서 애니메이션의 각 프레임에 대해 캔버스를 지우고 새로운 원점 좌표로 새 원을 그립니다.

단계별로 코드를 실행하면 clearRect 기능이 제대로 작동하지만 캔버스가 다시 그려 질 때마다 첫 번째 서클 중심에서부터 시작점까지의 직선을 포함하여 새 원과 모든 이전 원이 그려집니다. 새 서클 센터.

파일 index.html :

<!DOCTYPE html> 
    <html> 
    <head> 
     <meta charset="UTF-8"> 
     <title>my website</title> 
    </head> 
    <body onLoad="init();"> 
     <canvas class="circle" id="pinkCircle" width="400" height="400" 
     style="border:1px solid pink;"> 
     </canvas> 
     <script src="js/myjs.js"></script> 
    </body> 
    </html> 

파일 js/myjs.js는 :

//set variables 
    var canvas; 
    var context; 
    var myCircle = {x:50,y:100,r:20}; 
    //offset 
    var dx = 8; 
    var dy = 5; 
    function init() { 
    //set canvas and its context 
    canvas = document.getElementById('pinkCircle'); 
    context = canvas.getContext('2d'); 
    //repeat the drawCircle function for each frame 
    setInterval(drawCircle,1000); 
    } 
    function drawCircle() { 
    //clear the canvas 
    context.clearRect(0,0,canvas.width,canvas.height); 
    //redraw a circle with a different origin coordinates each time 
    context.beginPath; 
    context.arc(myCircle.x, myCircle.y, myCircle.r, 0, 2 * Math.PI, true); 
    context.closePath(); 
    context.stroke(); 
    if(myCircle.x<0 || myCircle.x>400) dx=-dx; 
    if(myCircle.y<0 || myCircle.y>400) dy=-dy; 
    myCircle.x+=dx; 
    myCircle.y+=dy; 
    } 

나는 온라인 리소스를 많이 겪었지만 나는 무엇이 잘못되었는지 알아낼 수 없습니다.

답변

2

코드가 거의 정확합니다. 하지만 당신은 하나의 작은 실수를 :

context.beginPath; 

그것은해야한다 : JS Bin Link

+0

대괄호를 추가하면 문제가 해결되었습니다. – zone12

0

근무

context.beginPath(); 

당신의 Autoredraw 속성을 확인해 봤어 아래 줄에 괄호를 준하지 않았나요 페이지? 나는 그것이 귀하의 경우 거짓으로 설정되어야한다고 생각합니다.

관련 문제