Rotating the Player Ship from the Center

The code to rotate the player ship from its center point is almost exactly like the code used to rotate it at the top-left corner. What we need to modify is the point of the translation. In Example 8-5, we placed the immediate-mode drawing context at the x and y coordinates of our game object (50,50). This had the effect of rotating the object from the top-left corner. Now we must move the translation to the center of our object:

context.translate(x+.5*width,y+.5*height);

Note

The width and height variables represent attributes of our drawn player ship. We will create these attributes in Example 8-6.

This is not the only change we need to make; we also need to draw our ship as though it is the center point. To do this, we will subtract half the width from each x attribute in our path draw sequence, and we will subtract half the height from each y attribute:

context.moveTo(10-.5*width,0-.5*height);
context.lineTo(19-.5*width,19-.5*height);

As you can see, it might get a little confusing trying to draw coordinates in this manner. It is also slightly more processor-intensive than using constants. In that case, we would simply hardcode in the needed values. Remember, the width and height attributes of our ship are both 20. The hardcoded version would look something like this:

context.moveTo(0,10);  //10-10, 0-10
context.lineTo(9,9); //19-10, 19-10

The method where we use the calculated values (using the width and height variables) is much more flexible, ...

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.