Falcon80 Logo
Save and restoring attributes on canvas

When you use the save() method, all the attributes that you define before save() are pushed into a stack You can push any number of attribute sets into the stack. You can then ues the restore() method to pop each set of attributes out of the stack in the reverse order in which they were pushed in.

In the following example, I am saving three sets of attributes and then restoring them one by one for every fillText() method. When you execute the code, notice that the attributes of the text get applied in the reverse order.

What can you store using the save() method?

You can save the following attributes: lineWidth, lineCap, lineJoin, miterLimit, strokeStyle, fillStyle, createLinearGradient, createRadialGradient, createPatterns, shadowColor, shadowOffsetX, shadowOffsetY, shadowBlur, globalCompositeOperation, font, textAlign, textBaseline.

You can also save transformations, and clipping regions. 

HTML Code
<html>
<head>
  <script type="application/javascript">
function init() {
var canvas = document.getElementById("canvas");
if (canvas.getContext)
{
var ctx = canvas.getContext("2d");

//This is attribute set 1
ctx.font = "25px verdana";
ctx.fillStyle = "yellow";
ctx.shadowOffsetX = 3;
ctx.shadowOffsetY = 3;
ctx.shadowBlur = 2;
ctx.shadowColor = "grey";

//Let's push the attributes into the stack. Since this set of attributes is the first one into the stack, it will be the last one out
ctx.save();

//This is attribute set 2
var fillColor = ctx.createLinearGradient(100,10,200,10);
fillColor.addColorStop(0.4,"red");
fillColor.addColorStop(0.6,"green");
ctx.fillStyle = fillColor;
ctx.shadowOffsetX = 3;
ctx.shadowOffsetY = 3;
ctx.shadowBlur = 2;
ctx.shadowColor = "pink";

// Push attribute set 2 into the stack. This will be the second set to be restored.
ctx.save();


//This is attribute set 3
ctx.fillStyle = "rgba(0,0,255,0.5)";
ctx.shadowOffsetX = 3;
ctx.shadowOffsetY = 3;
ctx.shadowBlur = 2;
ctx.shadowColor = "rgb(200,255,200)";

//Push attribute set 3 into the stack. This is the last set we are pushing inside. So it will be the first one to be restored.
ctx.save();

// Start popping the stack. Restore attribute set 3
ctx.restore();
ctx.fillText("Believe",5,20);

// Restore attribute set 2
ctx.restore();
ctx.fillText("Believe",100,20);

//Restore attribute set 1
ctx.restore();
ctx.fillText("Believe", 200,20);

}
}
  </script>
<title> Compositing on canvas </title>
</head>
<body onload="init();">
<canvas id="canvas" width="900" height="500"></canvas><br>
</body>
</html>

Note: Try out the other compositing options in the above code to see how they work. Also, note that the globalCompositeOperation attribute affects all drawing on the canvas.

Try Code