Canvas
by GarfieldKlon
HTML
<!DOCTYPE html>
<html>
<head>
<title>Canvas</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" type="text/css" href="canvas.css">
</head>
<body>
<canvas></canvas>
<script src="canvas.js"></script>
</body>
</html>
JavaScript
let canvas = document.querySelector("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const ctx = canvas.getContext("2d");
function Circle(x, y, dx, dy, radius) {
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
this.radius = radius;
this.draw = function () {
const red = Math.random() * 255;
const green = Math.random() * 255;
const blue = Math.random() * 255;
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
//ctx.strokeStyle = "blue";
//ctx.stroke();
ctx.fill();
//ctx.fillStyle = `rgb(${red}, ${green}, ${blue})`;
ctx.fillStyle = "red";
};
this.update = function () {
if (this.x + this.radius > innerWidth || this.x - this.radius < 0) {
this.dx = -this.dx;
}
if (this.y + this.radius > innerHeight || this.y - this.radius < 0) {
this.dy = -this.dy;
}
this.x += this.dx;
this.y += this.dy;
// for testing purpose (what happens if something needs more time than an animationframe ~16ms on a 60hz monitor)
for (let i = 0; i < 10000000; i++) {
//noop
}
this.draw();
};
}
const circles = [];
for (let i = 0; i < 100; i++) {
const radius = 30;
let x = Math.random() * (innerWidth - radius * 2) + radius;
let y = Math.random() * (innerHeight - radius * 2) + radius;
let dx = (Math.random() - 0.5) * 1;
let dy = (Math.random() - 0.5) * 1;
circles.push(new Circle(x, y, dx, dy, radius));
}
function animate() {
requestAnimationFrame(animate);
ctx.clearRect(0, 0, window.innerWidth, window.innerHeight);
for (let i = 0; i < circles.length; i++) {
//setTimeout(circles[i].update.bind(circles[i]), 1000);
circles[i].update();
}
}
animate();