var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var h = canvas.height;
var w = canvas.width;
var sAngle = 0;
var numB = 10;
var speed = 50;
var dt = 0.01;
const PI = Math.PI;
function resetCanvas () {
canvas.width = canvas.width;
};
function createBalls (){
for(var i = 1; i <= numB; i++){
if (i % 2 == 0) {
window['ball' + i] =
{r:10, color:"white", x:w*Math.random(), y:h*Math.random(), v:speed}} else {
window['ball' + i] =
{r:10, color:"white", x:w*Math.random(), y:h*Math.random(), v:-1 *speed}};
}
}
createBalls();
function drawBalls () {
for (var i = 1; i <= numB; i++) {
ctx.beginPath();
ctx.arc(window['ball' + i].x, window['ball' + i].y, window['ball' + i].r, sAngle, 2*PI);
ctx.fillStyle = window['ball' + i].color;
ctx.fill();
ctx.strokeStyle = window['ball' + i].color;
ctx.stroke();
}
}
drawBalls();
function moveBalls () {
for (var i = 1; i <= numB; i++) {
if (0 < window['ball' + i].x < w && 0 < window['ball' + i].y < h)
{window['ball' + i].x = window['ball' + i].x + window['ball' + i].v * dt;
window['ball' + i].y = window['ball' + i].y + window['ball' + i].v * dt}
if (window['ball' + i].x < 0 || window['ball' + i].x > w)
{window['ball' + i].x = window['ball' + i].x + ((-1) * window['ball' + i].v * dt);
window['ball' + i].y = window['ball' + i].y + window['ball' + i].v * dt}
if (window['ball' + i].y < 0 || window['ball' + i].y > h)
{window['ball' + i].y = window['ball' + i].y + ((-1) * window['ball' + i].v * dt);
window['ball' + i].x = window['ball' + i].x + window['ball' + i].v * dt}
}
}
function animate () {
resetCanvas();
drawBalls();
moveBalls();
};
setInterval(animate, 100 * dt);
I'm trying to make the balls bounce off the canvas walls in the opposite direction; however, right now they just hit the canvas border and slide to the corners and disappear. Any ideas on how I can improve the if conditions in my moveBall function so that the balls bounce off the canvas walls?