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 lines:

world.Step(1 / 60, 10, 10);

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

<!doctype html>
<html lang="en">
<meta charset="UTF-8">
<title>CH5EX20:  Box2dWeb Balls Demo</title>
<script src="modernizr.js"></script>
<script type="text/javascript" src="Box2dWeb-2.1.a.3.js"></script> ...

Get HTML5 Canvas, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.