var canvas = document.querySelector("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var ctx = canvas.getContext("2d");
function rectangle(x, y, dx, dy) {
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
this.draw = function() {
ctx.beginPath();
ctx.rect(this.dx, this.dy, this.x, this.y);
ctx.fillStyle = "blue";
ctx.fill();
ctx.strokeStyle = "green";
ctx.stroke();
}
this.dipendu = function() {
if (this.dx + this.x > innerWidth || this.dx - this.x < 0) {
this.dx = -this.dx;
}
if (this.dy + this.y > innerHeight || this.dy - this.y < 0) {
this.dy = -this.dy;
}
this.x += this.dx;
this.y += this.dy;
this.draw();
}
}
var rcontainer = [];
for (var i = 0; i <= 100; i++) {
var x = Math.random() * innerWidth;
var y = Math.random() * innerHeight;
var dx = Math.random() * innerWidth;
var dy = Math.random() * innerHeight;
rcontainer.push(new rectangle(x, y, dx, dy));
}
function animation() {
requestAnimationFrame(animation);
ctx.clearRect(0, 0, innerWidth, innerHeight);
for (var j = 0; j <= rcontainer.length; j++) {
rcontainer.update();
}
}
animation();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>motion</title>
<style>
#mycanvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="mycanvas"></canvas>
<script src="motion.js"></script>
</body>
</html>