Rendering the Boxes

To render the boxes, we loop through the boxes array in drawScreen() in a similar manner to how we looped through the balls in CH5EX22.html. We retrieve the position and shape using GetPosition() and GetShape(), preparing to render the boxes:

for (i =0;i <boxes.length;i++) {
   var position = boxes[i].GetPosition();
   var fixtureList = boxes[i].GetFixtureList();
   var shape = fixtureList.GetShape();

However, because these are boxes that fall and rotate, we need to perform some significantly different operations to render the boxes correctly. First we retrieve the object we saved in the user data attached to the body by calling GetUserData():

   var userData = boxes[i].GetUserData();

Next we save the Canvas context, reset the transformation matrix, and translate to the center of the box. Because the origin of the objects in Box2D is set to the center, we don’t have to offset to the center for our transformation. Next we rotate the Canvas to the angle of the box. We find the angle with a call to GetAngle():

    context.save();
    context.setTransform(1,0,0,1,0,0);
    context.translate(position.x * scaleFactor,position.y * scaleFactor);
    context.rotate(boxes[i].GetAngle());

To draw the box, we need to offset the x and y from the position back to ½ width and height because we draw on the Canvas with an origin at the upper-left corner. Then we restore the context, and we are done with the box:

context.fillRect(0-(userData.width*scaleFactor/2), 0-
                   (userData.height*scaleFactor/2),
       userData

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.