Reputation: 67
How can you add multiple balls to this code ?
Ideally I would like to send to a function X amount of balls to be displayed on the canvas.
var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext("2d");
var p = { x: 25, y: 25 };
var velo = 3,
corner = 50,
rad = 20;
var ball = { x: p.x, y: p.y };
var moveX = Math.cos((Math.PI / 180) * corner) * velo;
var moveY = Math.sin((Math.PI / 180) * corner) * velo;
function DrawMe() {
ctx.clearRect(0, 0, 400, 300);
if (ball.x > canvas.width - rad || ball.x < rad) moveX = -moveX;
if (ball.y > canvas.height - rad || ball.y < rad) moveY = -moveY;
ball.x += moveX;
ball.y += moveY;
ctx.beginPath();
ctx.fillStyle = "red";
ctx.arc(ball.x, ball.y, rad, 0, Math.PI * 2, false);
ctx.fill();
ctx.closePath();
}
setInterval(DrawMe, 10);
Upvotes: 0
Views: 1103
Reputation: 336
You could have the "DrawMe" function take in the "ball" as a parameter, and instead of just having 1 ball, you could have an array of balls, and on each tick of the "setInterval" call, you could update all of the different balls by looping through the array and calling "DrawMe" for each ball. Just one way :)
Upvotes: 1