Bouncing balls in canvas showing weird behaviour when more than two balls are created

1k views Asked by At

The following is my script part which i edited from an online tutorial , if I have two balls it is working fine , but if have have more than 2 balls it is not working as desired

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;
}

If I comment any two context.arc calls the balls are bouncing fine , but when it is more than two calls the same the balls are displayed in some weird pattern , not as individual balls

1

There are 1 answers

1
tom On BEST ANSWER

You need to break the paths between the balls, either by calling beginPath() and fill() for each circle or by using moveTo() to skip from one to the next without leaving a path.

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();

Demo: http://jsfiddle.net/5Mj5U/

Improved demo: http://jsfiddle.net/7nJDV/