HTML5 Game - Saving and Restoring Drawing State

Introduction

We can save the drawing state and return to it later using the methods in the following table.

ValueDescription
save() Saves the values for the drawing state properties and pushes them on the state stack
restore()Pops the first set of values from the state stack and uses them to set the drawing state

The saved drawing states are stored in a last-in, first-out stack.

The last state we saved using the save method is the first one restored by the restore method.

Demo

ResultView the demo in separate window

<!DOCTYPE HTML>
<html>
    <head>
        <title>Example</title>
        <style>
            canvas {border: thin solid black; margin: 4px}
        </style>
    </head>
    <body>
        <canvas id="canvas" width="500" height="140" preload="auto">
            Your browser doesn't support the <code>canvas</code> element
        </canvas>
        <div>
            <button>Save</button>
            <button>Restore</button>
        </div>
        <script>
            let ctx = document.getElementById("canvas").getContext("2d");
            //from   ww  w  . ja v a  2  s  .  c  om
            let grad = ctx.createLinearGradient(500, 0, 500, 140);
            grad.addColorStop(0, "red");
            grad.addColorStop(0.5, "white");
            grad.addColorStop(1, "black");

            let colors = ["black", grad, "red", "green", "yellow", "black", "grey"];
            
            let cIndex = 0;
            
            ctx.fillStyle = colors[cIndex];
            draw();
            
            let buttons = document.getElementsByTagName("button");
            for (let i = 0; i < buttons.length; i++) {
                buttons[i].onclick = handleButtonPress;
            }
            
            function handleButtonPress(e) {
                switch (e.target.innerHTML) {
                    case 'Save':
                        ctx.save();
                        cIndex = (cIndex + 1) % colors.length;
                        ctx.fillStyle = colors[cIndex];
                        draw();
                        break;
                    case 'Restore':
                        cIndex = Math.max(0, cIndex -1);
                        ctx.restore();
                        draw();
                        break;
                }
            }
            function draw() {
                ctx.fillRect(0, 0, 500, 140);
            }
        </script>
    </body>
</html>

The contents of the canvas are not saved or restored; only the property values for the drawing state are saved or restored.

Related Topic