How does "Restore" and "save" work?

Asked

Viewed 445 times

1

I was trying to understand the workings of the methods save and restore of canvas and I looked on the page of MDN.

I still don’t understand what the difference is between using them or not.

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

But I still can’t understand what the use of them did in this 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 method restore and save?

How this state works?

  • 1

    Back to the previous state, "black pen".

  • @Bacco nooooooooooooooooooooooooooooooosa, I didn’t even touch, man! kkkkkkkk

1 answer

4


Basically the .save keeps the current state of the context:

  • The current transformation matrix;
  • the cut-off region;
  • the dashed list;
  • and the values of all these attributes:

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

Documentation:

https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/save

The .restore returns to the previous state. Very useful when you will 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.