HTML5 Game - Canvas Rotate

Introduction

The following code shows how to rotate the canvas.

The code first positions the canvas context with a translation transform, and then rotate the context with rotate() method.

Demo

ResultView the demo in separate window

<html>
    <head>
        <script>
            window.onload = function(){
                let canvas = document.getElementById("myCanvas");
                let context = canvas.getContext("2d");
                /*from   w w w.j a va2s . c o  m*/
                let rectWidth = 150;
                let rectHeight = 75;
                
                // translate context to center of canvas
                context.translate(canvas.width / 2, canvas.height / 2);
        
                // rotate context 45 degrees clockwise
                context.rotate(Math.PI / 4);
                
                context.fillStyle = "blue";
                context.fillRect(-rectWidth / 2, -rectHeight / 2, rectWidth, rectHeight);
            };
        </script>
    </head>
    <body>
        <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;">
        </canvas>
    </body>
</html>

Note

To position and rotate the rectangle, translate the canvas context to the center of the canvas.

Then we rotate the canvas context using the rotation transform.

canvas.rotate(theta); 

The parameter theta is in radians.

The transform rotates the context clockwise.

After that we can then draw the rectangle centered on the top-left corner of the context.

Related Topics