bouncing
by DSDmark
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>bouncing</title>
<link rel="stylesheet" href="assets/css/style.css" />
</head>
<body>
<canvas id="cvs"></canvas>
<script src="assets/js/index.js"></script>
</body>
</html>
CSS
body {
margin: 0;
padding: 0;
box-sizing: border-box;
display: grid;
place-items: center;
min-height: 100vh;
background: rgb(211, 211, 211);
}
JavaScript
const canvas = document.getElementById("cvs");
const ctx = canvas.getContext("2d");
const CH = (canvas.height = 400);
const CW = (canvas.width = 400);
canvas.style.background = "black";
canvas.style.border = "1rem solid white";
const bounceBall = {
speed: 3,
velocity_x: 2,
velocity_y: 2,
radius: 50,
color: "white",
angle: 0,
position: {
x: CW / 2,
y: CH / 2,
},
draw() {
ctx.clearRect(0, 0, CH, CW);
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.position.x, this.position.y, this.radius, 0, 2 * Math.PI);
ctx.closePath();
ctx.fill();
},
update() {
if (
this.position.x + this.radius > CW ||
this.position.x - this.radius < 0
) {
this.velocity_x = -this.velocity_x;
this.color = "green";
}
if (
this.position.y + this.radius > CH ||
this.position.y - this.radius < 0
) {
this.velocity_y = -this.velocity_y;
this.color = "red";
}
if (this.position.y - this.radius < 0 || this.position.x < 0) {
this.angle = Math.PI / 4;
} else {
this.angle = Math.PI / 4;
}
this.position.x += this.velocity_x;
this.position.y += this.velocity_y;
},
};
function render() {
bounceBall.draw();
bounceBall.update();
}
function gameLoop() {
render();
}
setInterval(() => {
gameLoop();
}, 1000 / 60);