How to Make a Bouncing Ball Animation in HTML
Mastering the ability to make a bouncing ball animation in HTML is a fundamental step for game developers that will permit you to go on to bigger and better projects. The whole process centers around "canvas," an HTML5 tag that permits you to construct a frame, fill the frame with a shape and then move the shape in whatever fashion you would like.
Instructions
-
Create a Ball
-
1
Create a basic HTML document using the "html," "head" and "body" tags:
<html>
<head>
</head>
<body>
</body>
</html> -
2
Insert a "canvas" tag between the "body" tags and assign it an ID, a width and a height. The canvas represents the space where the ball will bounce:
<canvas id="bouncing_ball_canvas" width="500" height="500">
</canvas> -
-
3
Setup a JavaScript module between the "head" tags:
<script type="text/javascript">
</script> -
4
Establish variables for the canvas, the ball's initial "x" coordinate, the ball's initial "y" coordinate, and the amounts the ball should move along the "x" and "y" axes each iteration:
var canvas_variable;
var init_x = 200;
var init_y = 100;
var x_move = 5;
var y_move = 5; -
5
Build a JavaScript function that stores the canvas in a variable:
function initialize_canvas()
{
canvas_variable = bouncing_ball_canvas.getContext('2d');
} -
6
Construct a JavaScript function that clears the canvas, initializes a canvas shape, initializes a canvas color, draws the shape as a ball, stops drawing and then fills the shape with the previously initialized color:
function draw_ball()
{canvas_variable.clearRect(0,0, 500, 500);
canvas_variable.beginPath();
canvas_variable.fillStyle="#FF0000";
canvas_variable.arc(init_x, init_y, 30, 0, Math.PI*2, true);
canvas_variable.closePath();
canvas_variable.fill();}
Note that the values in canvas_variable.clearRect pertain to the canvas's initial x coordinate, initial y coordinate, width and height.
Note that the values in canvas_variable.arc refer to the ball's initial x coordinate, initial y coordinate, starting angle, ending angle and clockwise/anti-clockwise status.
-
7
Supplement the second function with code that checks whether the initial "x" and "y" variables have crossed beyond the canvas's boundary, and changes the positive/negative sign of the x and y move variables. Follow it with code that increases the initial "x" and "y" coordinate variables by the move variables:
if( init_x<0 || init_x>500) x_move = -x_move;
if( init_y<0 || init_y>500) y_move = -y_move;init_x += x_move;
init_y += y_move; -
8
Adjust the first function with code that calls the second function every 15 milliseconds:
setInterval(draw_ball, 15);
-
9
Load the first function into the document's body by adjusting the first "body" tag:
<body onLoad="initialize_canvas();">
-
1
References
Resources
- Photo Credit George Doyle/Stockbyte/Getty Images