<!DOCTYPE html>
<html>
<meta charset="utf-8">
<canvas width="600" height="400"></canvas>
</html>
<script type="text/javascript">
var myCanvas = document.querySelector('canvas');
var brush = myCanvas.getContext('2d');
var screenWidth = myCanvas.width;
var screenHeight = myCanvas.height;
const ball = {
radius: 15,
color: 'white',
X: screenWidth / 2,
Y: screenHeight / 2,
speedX: 1.5,
speedY: 0.5
};
setInterval(updateScreen, 10);
function drawCircle (X, Y, radius, color) {
brush.beginPath();
brush.fillStyle = color;
brush.arc(X, Y, radius, 0, 2 * Math.PI);
brush.fill();
}
function clearScreen () {
brush.clearRect(0, 0, screenWidth, screenHeight);
brush.fillStyle = 'black';
brush.fillRect(0, 0, screenWidth, screenHeight);
}
function updateScreen () {
clearScreen();
ballMovement();
drawCircle(ball.X, ball.Y, ball.radius, ball.color);
}
function ballMovement () {
if (ball.X - ball.radius - myCanvas.offsetLeft >= 0 &&
ball.X + ball.radius <= screenWidth) {
ball.X += ball.speedX;
}
else {
ball.speedX = -1 * ball.speedX;
ball.X += ball.speedX;
}
if (ball.Y - ball.radius - myCanvas.offsetTop > 0 &&
ball.Y + ball.radius < screenHeight) {
ball.Y += ball.speedY;
}
else {
ball.speedY = -1 * ball.speedY;
ball.Y += ball.speedY;
}
}
</script>