Translating to the Canvas
So far, we have looked only at Box2D output with b2DebigDraw. While this looks neat, it’s not
really useful for Canvas applications. As we stated earlier, Box2D is
just a “physics model.” It is your job to apply that model to the HTML5
Canvas. In this next example, we will take the bouncing balls from the
last example and show them running side-by-wide with the Canvas. (See
Figure 5-27.)

Figure 5-27. Bouncing balls in Box2D on the Canvas and in b2DebugDraw
The first thing we need to do is to define a second Canvas in our
HTML to show the b2DebugDraw
output:
<canvasid="canvasOne"width="450"height="350">Your browser does not support the HTML 5 Canvas.</canvas><canvasid="canvasTwo"width="450"height="350">Your browser does not support the HTML 5 Canvas.</canvas>
Notice that the Canvas is now smaller (450×350). We changed the size so that we could easily fit two Canvases side by side in the web browser. We also need to make sure to get a reference to both in our JavaScript code:
vartheCanvas=document.getElementById('canvasOne');varcontext=theCanvas.getContext('2d');vartheCanvasTwo=document.getElementById('canvasTwo');varcontext2=theCanvasTwo.getContext('2d');
Now that we have that out of the way, let’s start by making our
lives a lot easier. Instead of using a literal for our scale factor, we
will create a variable named scaleFactor that we ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access