HTML and CSS Reference
In-Depth Information
world . DrawDebugData ();
world . ClearForces ();
Now we are going to translate the Box2D data in our model to the Canvas. Most of this
drawScreen() functionshouldlookfamiliar,becauseitisnotmuchdifferentthansomeofthe
earlier bouncing ball demos. First we clear the Canvas, and then we look through the balls
array to display each ball:
context . fillStyle = '#EEEEEE' ;
context . fillRect ( 0 , 0 , theCanvas . width , theCanvas . height );
//Box
context . strokeStyle = '#000000' ;
context . strokeRect ( 1 , 1 , theCanvas . width - 2 , theCanvas . height - 2 );
for
for ( i = 0 ; i < balls . length ; i ++ ) {
The first big difference is how we get the position and size of the ball we are going to draw.
The items we have in our balls array are instances of the Box2D b2Body object. We use that
object's GetPosition() method to find the current x and y coordinates of the ball. We then
call the GetFixtureList() method of b2Body . This will give us the b2Fixture we created
for the ball. Recall that for each fixture we set a shape property. We need to get that shape
property by calling fixtureList.GetShape() :
var
var position = balls [ i ]. GetPosition ();
var
var fixtureList = balls [ i ]. GetFixtureList ();
var
var shape = fixtureList . GetShape ();
With all the information we need, we can now draw the ball on the Canvas. Using the con-
text.arc() method, we set the x and y position multiplied by the scaleFactor (because we
are now converting from MTS units to pixels). We call shape.GetRadius() for the size of
the circle and use the same conversion with scaleFactor :
context . fillStyle = "#000000" ;
context . beginPath ();
context . arc ( position . x * scaleFactor , position . y *
scaleFactor , shape . GetRadius () * scaleFactor , 0 , Math . PI * 2 , true
true );
context . closePath ();
context . fill ();
}
Whenyouruntheexample( CH5EX22.html ),youwillseesomethingsimilartowhatisin Fig-
ure 5-27 The Canvas on the left displays balls using the Canvas drawing objects and looks
very similar to the demo we created in CH5EX8.html . The Canvas on the right shows the
Search WWH ::




Custom Search