HTML Canvas Context Rotate

Introduction

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

It rotates the context about the top-left corner of the context:

canvas.rotate(theta); 

View in separate window

<html>
    <head>
        <script>
            window.onload = function(){
                var canvas = document.getElementById("myCanvas");
                var context = canvas.getContext("2d");
                /*www . jav  a  2  s  .c o m*/
                var rectWidth = 150;
                var 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>



PreviousNext

Related