2013-09-03 3 views
2

다음은 온라인 튜토리얼에서 편집 한 내 스크립트 부분입니다. 두 개의 공이 있으면 잘 작동하지만 두 개 이상의 공이 있다면 나는 공을 잘 수신 거부하는 호출 context.arc 두를 언급하면 ​​원하는두 개 이상의 공이 생성되면 이상한 동작을 보여주는 캔버스의 튀는 공

script.js

var context; 
var x=0;var y=0;var dx=3;var dy=7; 
var x_1=150;var y_1=250;var dx_1=7;var dy_1=3; 
var x_2=200;var y_2=200;var dx_2=6;var dy_2=4; 
var x_3=350;var y_3=350;var dx_3=4;var dy_3=6; 

function init() 
{ 
    context= myCanvas.getContext('2d'); 
    setInterval(draw,10); 
} 

function draw() 
{ 
    context.clearRect(0,0, 500,500); 
    context.beginPath(); 
    context.fillStyle="#0000ff"; 

    context.arc(x,y,10,0,Math.PI*2,true); 
    context.arc(x_1,y_1,10,0,Math.PI*2,true); 
    context.arc(x_2,y_2,10,0,Math.PI*2,true); 
    context.arc(x_3,y_3,10,0,Math.PI*2,true); 
    context.closePath(); 

    context.fill(); 

    boundaryLogic(); 

function boundaryLogic() 
{ 
    if (x < 0 || x > 500) dx = -dx; 
    if (y < 0 || y > 500) dy = -dy; 
    x += dx; 
    y += dy; 

    if (x_1 < 0 || x_1 > 500) dx_1 = -dx_1; 
    if (y_1 < 0 || y_1 > 500) dy_1 = -dy_1; 
    x_1 += dx_1; 
    y_1 += dy_1; 

    if (x_2 < 0 || x_2 > 500) dx_2 = -dx_2; 
    if (y_2 < 0 || y_2 > 500) dy_2 = -dy_2; 
    x_2 += dx_2; 
    y_2 += dy_2; 

    if (x_3 < 0 || x_3 > 500) dx_3 = -dx_3; 
    if (y_3 < 0 || y_3 > 500) dy_3 = -dy_3; 
    x_3 += dx_3; 
    y_3 += dy_3; 
} 

로 일하고 것이 아니라, 그것은 공은 좀 이상한 패턴으로 표시됩니다 같은 두 개 이상의 통화를 때 , 개별 볼이 아닌 것

답변

2

각 서클에 대해 beginPath()fill()으로 전화하거나 moveTo()을 사용하여 경로를 벗어나지 않고 하나에서 다음으로 건너 뛰기 위해 볼 사이의 경로를 끊어야합니다.

context.beginPath(); 
context.arc(x,y,10,0,Math.PI*2,true); 
context.fill(); 
context.beginPath(); 
context.arc(x_1,y_1,10,0,Math.PI*2,true); 
context.fill(); 
context.beginPath(); 
context.arc(x_2,y_2,10,0,Math.PI*2,true); 
context.fill(); 
context.beginPath(); 
context.arc(x_3,y_3,10,0,Math.PI*2,true); 
context.fill(); 

데모 : http://jsfiddle.net/5Mj5U/

개선 데모 : http://jsfiddle.net/7nJDV/

+0

감사합니다,하지만 히며 closePath없이 두 볼이 작동 오는 방법()? –

+0

그들을 연결하는 보이지 않는 선이 있습니다. 3 개 이상이있을 때만 공 사이 모양이 보입니다. – tom