The Essential Guide to HTML5

(Greg DeLong) #1

Chapter 3


Bouncing Ball


In this chapter, we will cover:



  • creating programmer-defined objects

  • using setInterval for animation

  • drawing images

  • form input and validating form input

  • for loops

  • drawing with gradients


Introduction ...................................................................................................................................................


Animation, whether at the movies, using a flipbook, or generated by computer, involves displaying a
sequence of still images fast enough so that we interpret what we see as movement, as life. In this
chapter, Ill show you how to produce animated scenes by simulating a ball bouncing in a 2-dimensional
box, with horizontal and vertical speeds that can by changed by a player. The first iteration of our program
calculates new positions for the ball at fixed intervals of time and displays the result, and it also
determines when there would be a virtual collision of ball and wall and how the ball would bounce off the
wall. After that, well see how you can replace the ball with an image, and how to draw rectangles using
gradients. Lastly, well examine the HTML5 feature for validating form input. The three examples are



  • a ball bouncing in a 2-D box (Figure 3-1)

  • replace the ball with an image and use a gradient for the box walls (Figure 3-2)

  • validate the input (Figure 3-3)

Free download pdf