<script>
var context;
var xp = [];
var yp = [];
var numBalls = 5;
var dx = [];
var dy = [];
xMax = 500;
yMax = 500;
speedMax = 10;

function init()
{
  context= myCanvas.getContext('2d');

  // balls initial position
  for (i = 0 ; i < numBalls; i++) {
  	xp[i] = Math.floor(Math.random() * xMax);
  	yp[i] = Math.floor(Math.random() * yMax);
  	dx[i] = Math.floor(Math.random() * speedMax);
  	dy[i] = Math.floor(Math.random() * speedMax);
  }
  drawBalls();
  setInterval(drawBalls,20);
}

function drawBall(x,y)
{
  context.beginPath();
  context.fillStyle="#0000ff";
  // Draws a circle of radius 20 at the coordinates x,y on the canvas
  context.arc(x,y,20,0,Math.PI*2,true);
  context.closePath();
  context.fill();
}

function drawBalls() 
{
  context.clearRect(0,0, xMax,yMax);
  for (i = 0 ; i < numBalls; i++) { 
    // Boundary Logic
    if( xp[i]<0 || xp[i]>xMax) dx[i]=-dx[i];
    if( yp[i]<0 || yp[i]>xMax) dy[i]=-dy[i];
    xp[i]+=dx[i];
    yp[i]+=dy[i];
    drawBall(xp[i],yp[i]);
  }
}

</script>
<body onLoad="init();">
  <canvas id="myCanvas" width="500" height="500" >
  </canvas>
</body>
</body>
Topic revision: r1 - 2017-04-24 - JimSkon
 
This site is powered by the TWiki collaboration platform Powered by PerlCopyright © 2008-2019 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback