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.
// Basic styles for our line border and inner color
ctx.strokeStyle = "black";
ctx.lineWidth = 3;
ctx.fillStyle = "rgba(128, 128, 128, 0.5)";
// Save before we rotate so that after the rotation we can restore the context
// We are putting the square in the center of the canvas. We need to update the coordinate space of the context so that it rotates at the objects center point.
// Rotate using radians
// Draw the square
ctx.rect(-64, -64, 128, 128);
// Put the context back to the original rotation and position from before we translated it
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.