diff --git a/index.html b/index.html index 027d142..f671e7e 100644 --- a/index.html +++ b/index.html @@ -3,6 +3,5 @@ - \ No newline at end of file diff --git a/index.js b/index.js index ed8f2d2..9deb08b 100644 --- a/index.js +++ b/index.js @@ -1,26 +1,37 @@ "use strict"; -document.addEventListener('DOMContentLoaded', init); +document.addEventListener('DOMContentLoaded', () => init()); +let ctx, canvas = document.createElement("canvas"); function init() { - var canvas = document.getElementById("canvas"); - canvas.width = window.innerWidth - canvas.height = window.innerHeight + function start() { + canvas.width = window.innerWidth + canvas.height = window.innerHeight + ctx = canvas.getContext('2d'); + document.body.insertBefore(canvas, document.body.childNodes[0]); + document.addEventListener('keydown', controls); + run(); - const ctx = canvas.getContext('2d'); - var balls = []; - add(); - document.addEventListener('keydown', control); - - anim(); - - function control(e) { - switch(e.key) { - case 'ArrowUp': add(); break; - case 'ArrowDown': remove(); break; - } + for (let i = 0; i < 15; i++) add(); } + function run() { + ctx.clearRect(0, 0, canvas.width, canvas.height); + update(); + requestAnimationFrame(run); + } + + function controls(e) { + switch (e.key) { + case 'ArrowUp': add(); break; + case 'ArrowDown': remove(); break; + } + } + + // ------------------------------------------------------------------- + + let balls = []; + function remove() { balls.pop(); } @@ -30,40 +41,48 @@ function init() { let y = Math.floor(Math.random() * canvas.height); let speed = 1 + Math.floor(Math.random() * 10); let angle = Math.floor(Math.random() * 360); - - // angle must be in radians (now it's wrong) - balls.push({ x: x, y: y, size: 20, speed: speed, angle: angle, color:'black' }); + + balls.push(new ball(x, y, speed, angle)); + } + + function update() { + balls.forEach(b => b.update()); } - function anim() { - ctx.fillStyle = 'white'; - ctx.fillRect(0, 0, canvas.width, canvas.height); + start(); +} - balls.forEach(b => { - update(b); - draw(b); - } - ); - requestAnimationFrame(anim); +class ball { + constructor(x, y, speed, angle) { + this.x = x; + this.y = y; + this.speed = speed; + this.angle = angle; + this.color = 'black'; + this.size = 20; } - - function update(b) { - b.x += b.speed * Math.cos(b.angle); - b.y += b.speed * Math.sin(b.angle); - - if ( b.x<0 || b.x>canvas.width || b.y<0 || b.y>canvas.height ) bounce(b); + update() { + this.move(); + this.draw(); } - function bounce(b) { - b.angle += 180; + draw() { + ctx.fillStyle = this.color; + ctx.fillRect(this.x, this.y, this.size, this.size); } - function draw(b) { - ctx.fillStyle = b.color; - ctx.fillRect(b.x, b.y, b.size, b.size); + move() { + this.x += this.speed * Math.cos(this.angle); + this.y += this.speed * Math.sin(this.angle); + + if (this.x < 0 || this.x > canvas.width || this.y < 0 || this.y > canvas.height) + this.bounce(); } + bounce() { + this.angle += 180; + } }