Simple balls system

tutorial from mozilla

by schrodingers

CSS

* {
  overflow: hidden;
}

JavaScript

var canvas = document.createElement('canvas');
document.body.appendChild(canvas);
var ctx = canvas.getContext("2d");
var width = canvas.width = window.innerWidth;
var height = canvas.height = window.innerHeight;

function random(min, max) {
  var num = Math.floor(Math.random() * (max - min + 1)) + min;
  return num;
}

function Ball(x, y, vx, vy, color, size) {
  this.x = x;
  this.y = y;
  this.vx = vx;
  this.vy = vy;
  this.color = color;
  this.size = size;
}

Ball.prototype.draw = function() {
  ctx.beginPath();
  ctx.fillStyle = this.color;
  ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI);
  ctx.fill();
}

Ball.prototype.update = function() {
  if ((this.x + this.size) >= width) {
    this.vx = -this.vx;
  }
  if ((this.x - this.size) <= 0) {
    this.vx = -this.vx;
  }
  if ((this.y + this.size) >= height) {
    this.vy = -this.vy;
  }
  if ((this.y - this.size) <= 0) {
    this.vy = -this.vy;
  }
  this.x += this.vx;
  this.y += this.vy;
}

Ball.prototype.collisionDetect = function() {
  for (var j = 0; j < balls.length; j++) {
    if (!(this === balls[j])) {
      var dx = this.x - balls[j].x;
      var dy = this.y - balls[j].y;
      var dist = Math.sqrt(dx * dx + dy * dy);

      if (dist < this.size + balls[j].size) {
        balls[j].color = this.color = 'rgb(' + random(100, 190) + ',' + random(0, 255) + ',' + random(0, 255) + ')';
        balls[j].vx = -balls[j].vx;
        balls[j].vy = -balls[j].vy;
      }
    }
  }
}


var balls = [];

function loop() {
  ctx.fillStyle = 'rgba(0, 0, 0, 0.55)';
  ctx.fillRect(0, 0, width, height);

  while (balls.length < 25) {
    var ball = new Ball(
      random(0, width),
      random(0, height),
      random(-5, 5),
      random(-5, 5),
      'rgb(' + random(0, 100) + ',' + random(10, 255) + ',' + random(20, 255) + ')',
      random(10, 20)
    );
    balls.push(ball);
  }

  for (var i = 0; i < balls.length; i++) {
    balls[i].draw();
    balls[i].update();
    balls[i].collisionDetect();
  }
 ...