HTML5 Game - Handling multiple transforms with the state stack

Introduction

We can use the canvas state stack with transformations.

The state stack of canvas can manage styling and transformation states.

The following code will do multiple transformations and save the canvas state between each transformation.

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 . j  av  a2 s  .c om*/
                let rectWidth = 150;
                let rectHeight = 75;
                
                context.save(); // save state 1
                context.translate(canvas.width / 2, canvas.height / 2);
                
                context.save(); // save state 2
                context.rotate(Math.PI / 4);
                
                context.save(); // save state 3
                context.scale(2, 2);
                
                context.fillStyle = "blue";
                context.fillRect(-rectWidth / 2, -rectHeight / 2, rectWidth, rectHeight);
                
                context.restore(); // restore state 3
                context.fillStyle = "red";
                context.fillRect(-rectWidth / 2, -rectHeight / 2, rectWidth, rectHeight);
                
                context.restore(); // restore state 2
                context.fillStyle = "yellow";
                context.fillRect(-rectWidth / 2, -rectHeight / 2, rectWidth, rectHeight);
                
                context.restore(); // restore state 1
                context.fillStyle = "green";
                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

The code did three transformations:a translation, a rotation, and a scale transform.

It pushed each transformation state onto the state stack with the save() operation.

Related Topic