Let’s put a box around the court and bounce the ball when it hits the bottom.
<html>
<head>
<body>
<canvas id=”game_maze” width=”800″ height=”300″ style=’border-style:solid;’>
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>
<script>
//create ball on canvas
var gamemaze = document.getElementById(‘game_maze’);
var ball = gamemaze.getContext(’2d’);
ball.fillStyle = ‘grey’;
//initialize ball’s properties
oldxvector=1;
oldyvector=1;
xvector=1;
yvector=1;
//use a changeable variable for the amount to update the Y position.
increment=1;
//update ball’s position
Game_update = function() {
//get old ball properties to use in erasing it at it’s old position
oldxvector=xvector;
oldyvector=yvector;
//if ball hits edge change it’s trajectory with a bounce
if(oldyvector>290){
increment=-1;
}
//update ball position properties to move downward 45 degrees.
xvector=xvector+1;
yvector=yvector+increment;
};
Game_draw = function() {
ball.clearRect(oldxvector,oldyvector,5,5);
ball.fillRect(xvector,yvector,5,5);
};
//update the game logic and draw the game once every second
Game_fps = 40;
//loop logic and draw updates forever
Game_run = function() {
Game_update();
Game_draw();
};
// Start the game loop
Game_intervalId = setInterval(Game_run, 1000 / Game_fps);
</script>
</body>
</html>
