HTML5 Game - Rotating an image

Introduction

The following code rotates an image by translating and rotating the canvas context, and then drawing an image on the transformed context.

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  av a2s.com*/
                let imageObj = new Image();
                imageObj.onload = function(){
                    // translate context to center of canvas
                    context.translate(canvas.width / 2, canvas.height / 2);
                    
                    // rotate context by 45 degrees counter clockwise
                    context.rotate(-1 * Math.PI / 4);
                    context.drawImage(this, -1 * imageObj.width / 2, -1 * imageObj.height / 2);
                };
                
                imageObj.src = "http://java2s.com/style/download.png";
            };
        </script>
    </head>
    <body>
        <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;">
        </canvas>
    </body>
</html>

Note

To rotate an image, position the canvas context with the translate() method.

Then rotate the context with the rotate() method.

Finally draw the image with the drawImage() method.

Related Topic