JSFiddle - React, Tailwind, and code Playground
by kaotikus
HTML
<h1>bouncing balls</h1>
<p id="counter">ball count: </p>
<canvas></canvas>
CSS
html,
body {
margin: 0;
}
html {
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
height: 100%;
}
/* figure out what this means */
body {
overflow: hidden;
height: inherit;
}
h1 {
font-size: 2rem;
letter-spacing: -1px;
position: absolute;
margin: 0;
top: -4px;
right: 5px;
color: transparent;
/* read up on this */
text-shadow: 0 0 4px white;
}
#counter {
font-size: 1.2rem;
text-transform: capitalize;
position: absolute;
margin: 0;
color: white;
top: 42px;
right: 78px;
}
JavaScript
// setup canvas
var canvas = document.querySelector("canvas");
var ctx = canvas.getContext("2d");
var width = canvas.width = window.innerWidth;
var height = canvas.height = window.innerHeight;
// ball counter setup
//var counterText = document.getElementById("#counter");
//counterText.textContent = 0;
// function to generate random number
function random(min, max) {
var num = Math.floor(Math.random() * (max - min)) + min;
return num;
}
// define Shape constructor
function Shape(x, y, velX, velY, exists) {
this.x = x;
this.y = y;
this.velX = velX;
this.velY = velY;
this.exists = true;
}
// define Ball constructor
function Ball(x, y, velX, velY, color, size, exists) {
Shape.call(this, x, y, velX, velY, exists);
this.color = color;
this.size = size;
}
Ball.prototype = Object.create(Shape.prototype);
Ball.prototype.constructor = Ball;
// define ball draw method
Ball.prototype.draw = function() {
ctx.beginPath();
ctx.fillStyle = this.color;
ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI);
ctx.fill();
}
// define ball's update method
Ball.prototype.update = function() {
if ((this.x + this.size >= width)) {
this.velX = -(this.velX);
}
if ((this.x - this.size <= 0)) {
this.velX = -(this.velX);
}
if ((this.y + this.size) >= height) {
this.velY = -(this.velY);
}
if ((this.y - this.size) <= 0) {
this.velY = -(this.velY);
}
this.x += this.velX;
this.y += this.velY;
}
// define ball's collison detection
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 distance = Math.sqrt(dx * dx + dy * dy);
if (distance < this.size + balls[j].size) {
balls[j].color = this.color = "rgb(" + random(0, 255) + "," + random(0, 255) + "," + random(0, 255) + ")";
}
}
}
};
// define EvilCircle()
function EvilCircle(x, y, exists) {
...