How does "restore" and "save" methods work?

1

I was trying to understand the working of the save and restore methods of canvas and looked at the MDN .

Even though I still did not understand the difference between using them or not.

According to the documentation, save "saves a default state" and restore "restores that state later."

But I still can not understand what the use of them did in the example given there in the documentation:

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

ctx.save(); // save the default state

ctx.fillStyle = 'green';
ctx.fillRect(10, 10, 100, 100);

ctx.restore(); // restore to the default state
ctx.fillRect(150, 75, 100, 100);
<canvas id="canvas"></canvas>

What is the purpose of the restore and save method?

How does this state work?

    
asked by anonymous 15.01.2018 / 14:02

1 answer

4

Basically, .save saves the current state of the context:

  • The current transformation array;
  • a Clipping Region;
  • the dash list;
  • and the values of these attributes all:

    strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, lineJoin, miterLimit,
    lineDashOffset, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor,        
    globalCompositeOperation, font, textAlign, textBaseline, direction,
    imageSmoothingEnabled
    

Documentation:

  

link

The .restore returns to the previous state. Very useful when you are going to draw only a small detail differently from the rest. See:

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

// começamos com preenchimento verde
ctx.fillStyle = 'green';
ctx.fillRect(10, 10, 30, 100);

ctx.save(); // salvamos o estado

// mudamos o preenchimento pra azul
ctx.fillStyle = 'blue';
ctx.fillRect(50, 10, 30, 100);

ctx.restore(); // restauramos ao estado salvo

ctx.fillRect(90, 10, 30, 100);
// Notou que voltou ao verde?
<canvas id="canvas"></canvas>
    
15.01.2018 / 14:07