What Im trying to do is animate circles bouncing off the canvas borders. I can achieve that pretty will with just one ball. But my Home work asks of me to add a new ball every two seconds. Originally I tried this by making new objects listed in an array using a for loop, but had trouble coming up with a way to call "move" method out of each newly created object in an interval. At the end I settled with creating the variable j and setting it to 0 and having it increment by 10 since the interval will execute the function "startAnim" every 10 milliseconds. Then every two seconds have a new object created and then call that objects "move" method.
<!DOCTYPE html>
<html>
<head>
<title>Some document</title>
<body>
<h1></h1>
<canvas id="canvas" width = "400" height = "400"></canvas>
<script src= "https://code.jquery.com/jquery-2.1.0.js"></script>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var arrayOfCollor = ["green", "red", "blue","gold","black","purple"];
var ballFunction = function(){
this.x = 200;
this.y = 200;
this.xSpeed = 2;
this.ySpeed = -3;
this.radius = 10;
ctx.fillStyle = arrayOfCollor[Math.floor(Math.random() *
arrayOfCollor.length)];
}
ballFunction.prototype.draw = function(){
ctx.beginPath();
ctx.arc(this.x,this.y, this.radius, 0, Math.PI * 2, false);
ctx.fill();
}
ballFunction.prototype.move = function(){
ctx.clearRect(0,0,400,400);
ctx.strokeRect(0,0,400,400);
this.x += this.xSpeed;
this.y += this.ySpeed;
this.draw();
if(this.x > 400-this.radius|| this.x < 0 + this.radius){
this.xSpeed = -1* this.xSpeed;
}
if(this.y > 400 - this.radius || this.y < 0 + this.radius){
this.ySpeed = -1* this.ySpeed;
}
}
var j = 0;
function startAnim(){
j+= 10;
if( j === 2000){
var ballOne = new ballFunction
var ballOneInterval = setInterval(ballOne.move,10)
}
if( j === 4000){
var ballTwo = new ballFunction
var ballTwoInterval = setInterval(ballTwo.move,10)
}
if( j === 6000){
var ballThree = new ballFunction
var ballThreeInterval = setInterval(ballThree.move,10)
}
if( j === 8000){
var ballFour = new ballFunction
var ballFourInterval = setInterval(ballFour.move,10)
}
if( j === 10000){
var ballFive = new ballFunction
var ballFiveInterval = setInterval(ballFive.move,10)
}
if( j === 12000){
var ballSix = new ballFunction
var ballSixinterval = setInterval(ballSix.move,10)
}
}
var startAnimInt = setInterval(startAnim,10);
</script>
</body>
</html>
I keep receiving that the draw function is not a function at ballFunction.move even though I inserted it in.