Save a draw state

Description

save() saves the values for the drawing state properties.

Example

The following code draws three shapes, one circle and two rectangles. When drawing the first rectangle it sets the fill style to solid blue. Before drawing the circle it saves the drawing state by calling save() method. After painting the circle it restores back the saved drawing state and paints the second rectangle. We can see that the first and second rectangle share the same drawing style.


<!DOCTYPE HTML>
<html>
    <head>
        <script>
            window.onload = function(){<!--from   w w  w  .  j a va2s.  com-->
                var canvas = document.getElementById("myCanvas");
                var context = canvas.getContext("2d");
                
                // draw rectangle
                context.beginPath();
                context.rect(150, 30, 130, 130);
                context.fillStyle = "blue";
                context.fill();
                
                // wrap circle drawing code with save-restore combination
                context.save();
                context.globalAlpha = 0.5; // set global alpha
                context.beginPath();
                context.arc(canvas.width / 2, canvas.height / 2, 70, 0, 2 * Math.PI, false);
                context.fillStyle = "red";
                context.fill();
                context.restore();
                
                // draw another rectangle
                context.beginPath();
                context.rect(canvas.width - (150 + 130), canvas.height - (30 + 130), 130, 130);
                context.fill();
            };
        </script>
    </head>
    <body>
        <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;">
        </canvas>
    </body>
</html>

Click to view the demo





















Home »
  Javascript »
    Javascript Reference »




Array
Canvas Context
CSSStyleDeclaration
CSSStyleSheet
Date
Document
Event
Global
History
HTMLElement
Input Element
Location
Math
Number
String
Window