HTML5 Canvas Object Rotation

There is no simple function that you can use to rotate objects within the HTML5 Canvas. To implement rotation you need to rotate the entire canvas context and draw your object on the rotated context and then rotate the entire thing that back to it’s normal state. While you’re doing that, you also need to update the coordinate space of the canvas context.

Here’s how you might rotate a square.

If you’ve used the Canvas Drawing API before for simple tasks, most of this should be familiar. The concepts you might need to wrap your head around are the calls to ctx.save(), ctx.translate() and ctx.restore(). When we call ctx.save(), we are storing the drawing context’s current state where the coordinate space is at it’s default in the top left corner (0, 0) and there is no rotation. Once we finish drawing the rotated square, we will come back to this point.

We then call ctx.translate(), which changes the context’s coordinate space. It places it at 128, 128 which is going to be the center of our square (and actually the canvas). By default the coordinate space is always at 0, 0. The translate() method changes that.

After we update the coordinate space location we need to rotate it. We call ctx.rotate() and provide the value in radians. Finally, it’s just a matter of drawing the object. Notice the negative values in the call to rect(). We want to center the object on the coordinate space, so we need to move it halfway to the left (-64) and halfway up (-64) so that the center point is in the middle of the object. We use the restore() method to put the context back to it’s state before we rotated and moved it. Any objects added at this point will not be rotated.

Leave a Reply

Your email address will not be published. Required fields are marked *