HTML5 Game - Rotate 45 degrees (Math.PI/4)

Introduction

You just pass in the angle in radians that you want to rotate the 2d rendering context by:

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
                context.fillStyle = "red";   
                context.fillRect(50, 50, 100, 100);  

                context.rotate(0.7854); // Rotate 45 degrees (Math.PI/4)  


  
                context.fillStyle = "blue";  
                context.fillRect(50, 50, 100, 100);  

            };
        </script>
    </head>
    <body>
        <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;">
        </canvas>
    </body>
</html>

The result of this rotation might not be what you expected.

The rotate method rotates the 2d rendering context around its (0, 0) point of origin.

In the above code it is at the top left hand corner of the screen.

Because of this the square is not being rotated itself.

Demo

ResultView the demo in separate window

<html>
    <head>
        <script>
            window.onload = function(){
                let canvas = document.getElementById("myCanvas");
                let context = canvas.getContext("2d");
               /*  w  ww  .  ja v a2  s.c  o  m*/
                context.fillStyle = "red";   
                context.fillRect(50, 50, 100, 100);  

                context.translate(100, 100);
                context.rotate(0.7854); // Rotate 45 degrees (Math.PI/4)  


  
                context.fillStyle = "blue";  
                context.fillRect(-50, -50, 100, 100);  

            };
        </script>
    </head>
    <body>
        <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;">
        </canvas>
    </body>
</html>

Related Topic