Finally, we are ready to draw our Box2D physics models to the
HTML5 Canvas. To make that work, we replace all of
the code we have previously created in our
drawScreen() function with following three
world.Step() takes three parameters: time step, velocity iterations, and
position iterations. The time step is how much time in the simulation to
simulate on every call. For our application, we are simulating 1/60 of a
second. The other two parameters set the precision of the iterations and
should be left alone for now.
world.DrawDebugData() draws the
b2DebugDraw to the Canvas.
world.clearForces() is called after every step
to reset the physics model for the next step.
Example 5-20 provides the full code listing for CH1EX20.html. When you test this example, you will see 50 randomly created balls fall down and bounce off the bottom of the canvas. Some will bounce around for a long time, others will stop bouncing much sooner. Notice that balls appear to act the way you would expect balls to act. However, if you look back at the code we wrote, we did not create any functions for hit detection, angle of reflection, or linear movement. All of that was handled by Box2D.
Example 5-20. Box2dWeb balls demo
<title>CH5EX20: Box2dWeb Balls Demo