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:
<canvas
id=
"canvasOne"
width=
"450"
height=
"350"
>
Your browser does not support the HTML 5 Canvas.</canvas>
<canvas
id=
"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:
var
theCanvas
=
document
.
getElementById
(
'canvasOne'
);
var
context
=
theCanvas
.
getContext
(
'2d'
);
var
theCanvasTwo
=
document
.
getElementById
(
'canvasTwo'
);
var
context2
=
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 ...
Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.