Saving and restoring state

The canvas save and restore methods are used to save and retrieve the canvas state. The canvas drawing state is basically a snapshot of all the styles and transformations that have been applied. Both methods take no parameters.
 
Canvas states are stored on a stack. Every time the save method is called, the current drawing state is pushed onto the stack. A drawing state consists of

  • The transformations that have been applied (i.e. translate, rotate and scale – see below).
  • The values of strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, lineJoin, miterLimit, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation properties.
  • The current clipping path, which we’ll see in the next section.
  • You can call the save method as many times as you like.
    Every time the restore method is called, the last saved state is returned from the stack and all saved settings are restored.

    Example

    <!DOCTYPE HTML>
    <html>
        <head>
            <title>Canvas tutorial</title>
            <script>
                function draw(){
                    var ctx = document.getElementById('canvas').getContext('2d');
                    
                    // Draw a rectangle with default settings
                    ctx.fillRect(0, 0, 150, 150);
                    // Save the default state
                    ctx.save();
                    // Make changes to the settings
                    ctx.fillStyle = '#09F'
                    // Draw a rectangle with new settings
                    ctx.fillRect(15, 15, 120, 120);
                    
                    ctx.save(); // Save the current state
                    // Make changes to the settings
                    ctx.fillStyle = '#FFF'
                    ctx.globalAlpha = 0.5;
                    
                    // Draw a rectangle with new settings
                    ctx.fillRect(30, 30, 90, 90);
                    
                    ctx.restore(); // Restore previous state
                    // Draw a rectangle with restored settings
                    ctx.fillRect(45, 45, 60, 60);
                    
                    ctx.restore(); // Restore original state
                    // Draw a rectangle with restored settings
                    ctx.fillRect(60, 60, 30, 30);
                }
            </script>
        </head>
        <body onload="draw();">
            <canvas id="canvas" width="200" height="200">
            </canvas>
        </body>
    </html>