89 lines
2.0 KiB
JavaScript
89 lines
2.0 KiB
JavaScript
"use strict";
|
|
|
|
document.addEventListener('DOMContentLoaded', () => init());
|
|
|
|
let ctx, canvas = document.createElement("canvas");
|
|
function init() {
|
|
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();
|
|
|
|
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();
|
|
}
|
|
|
|
function add() {
|
|
let x = Math.floor(Math.random() * canvas.width);
|
|
let y = Math.floor(Math.random() * canvas.height);
|
|
let speed = 1 + Math.floor(Math.random() * 10);
|
|
let angle = Math.floor(Math.random() * 360);
|
|
|
|
balls.push(new ball(x, y, speed, angle));
|
|
}
|
|
|
|
function update() {
|
|
balls.forEach(b => b.update());
|
|
}
|
|
|
|
start();
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
update() {
|
|
this.move();
|
|
this.draw();
|
|
}
|
|
|
|
draw() {
|
|
ctx.fillStyle = this.color;
|
|
ctx.fillRect(this.x, this.y, this.size, this.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;
|
|
}
|
|
}
|
|
|
|
|