I've been working on a code project to create 10 bouncing balls of different colors, but I'm encountering an issue where only one or two balls appear with different colors or the animation works perfectly only 1 out of 10 times. Any thoughts on why this might be happening? Canvas Animation
<body>
<canvas id = "canvas" width="600" height = "500"> </canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var width = 300 //changes canvas size
var height = 400
width = canvas.width
height = canvas.height
/* In this constructor, the starting position
of the ball is set to this.x and this.y
*/
var Ball = function () {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.xSpeed = -2; // -2 means 2 pixels left for every step of animation.
this.ySpeed = 3;
var circle = function (x, y, radius, color, fill) { //function to make drawing circles faster
ctx.strokeStyle = color
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2, false);
if (fill === true) {
ctx.fillStyle = color;
ctx.fill()
}
ctx.stroke();
}
// The Ball maker
x = Math.floor(Math.random() * 10)
myColors = ["Green", "Red", "Orange", "Yellow", "Chocolate", "Brown", "Silver", "Black", "Purple", "Blue"]
Ball.prototype.draw = function () {
circle(this.x, this.y, 3, myColors[x], true)
};
// this will move the balls
Ball.prototype.move = function () {
this.x += this.xSpeed;
this.y += this.ySpeed;
};
Ball.prototype.checkCollision = function () { //makes the balls bounce off walls
if (this.x < 0 || this.x > width) {
this.xSpeed = -this.xSpeed;
}
if (this.y < 0 || this.y > height) {
this.ySpeed = -this.ySpeed;
}
}
}
var moBalls = [] //stores balls to be called later
for (var x = 0; x < 10; x++) {
moBalls[x] = new Ball()
}
width = canvas.width
height = canvas.height
setInterval(function () {
ctx.clearRect(0, 0, width, height);
for (x = 0; x < 10; x++) { //takes the balls from moBalls and moves the ten of them
moBalls[x].draw()
moBalls[x].move()
moBalls[x].checkCollision();
}
ctx.lineWidth = 4
ctx.strokeRect(0, 0, width, height); //makes the walls
}, 30);
</script>
</body>
</html>