Rotations

Rotations are made around the origin. In order to rotate around any other point, we translate that point to the origin, perform the rotation and translate back to the point's original position again, as shown below.

ctx.translate(canvas.width / 2, canvas.height / 2);
ctx.rotate(radiants);
ctx.translate(-canvas.width / 2, -canvas.height / 2);

Rotations are performed in radiants. We can convert from user friendly degrees to radiants using the formula below:

radiants = degrees * Math.PI / 180;

This can be achieved using the function below:

/* Convert from degrees to radians */
Math.radians = function (degrees)
{
    return degrees * Math.PI / 180;
};

By default, all drawing on the canvas after the rotation will be affected by the rotation. Normally, we do not want to do this.
Use the save() and restore() functions to limit the scope of a rotation, as shown below:

ctx.save();
ctx.translate(canvas.width / 2, canvas.height / 2);
ctx.rotate(Math.radians(90));
ctx.translate(-canvas.width / 2, -canvas.height / 2);

// anything drawn here will be rotated

ctx.restore();

Example showing text rotation (Run Example)

<!-- Author: Derek O Reilly, Dundalk Institute of Technology, Ireland. -->

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>GENIUS worked example</title>
        <style>
            #gameCanvas
            {
                /* the canvas styling usually does not change */
                outline:1px solid darkgrey;
                width:500px;
                height:500px;
            }
        </style>

        <script>
            /* Convert from degrees to radians */
            Math.radians = function (degrees)
            {
                return degrees * Math.PI / 180;
            };
        </script>
    </head>

    <body>
        <canvas id = "gameCanvas"></canvas>

        <script>
            let canvas = document.getElementById("gameCanvas");
            canvas.width = canvas.clientWidth;
            canvas.height = canvas.clientHeight;
            let ctx = canvas.getContext("2d");
            ctx.fillStyle = "black";
            ctx.font = "50px Times Roman";

            ctx.fillText("Normal Text", 100, 50);

            ctx.save();
            ctx.translate(canvas.width / 2, canvas.height / 2);
            ctx.rotate(Math.radians(45));
            ctx.translate(-canvas.width / 2, -canvas.height / 2);

            ctx.fillText("Diagonal Text", 100, 250);
            ctx.restore();
            ctx.fillText("Normal Again", 100, 450);
        </script>
    </body>
</html>

Everything inside the save()/restore() functions will be included in the rotaiton.

Write code to rotate an image by 90 degrees, as shown here. Remember that you need to ensure that the image is loaded before you attempt to draw it.