HTML5 canvas provides Save and restore methods to draw complex graphics.

It can save the state of canvas, including the translation, zooming, rotation, miscutting, cropping and other operations of canvas, and can also restore to the last saved state.

Related methods:

//Save the status of the current environment

//Return to previously saved path status and properties

The status of canvas is stored in memory. Its data structure is similar to stack, that is, it conforms to the basic characteristics of "first in, then out, then in, first out".

Calling the save method is equivalent to generating a snapshot of the current canvas state. It saves the snapshot in the snapshot pool and can be called any number of times, which is equivalent to the stack 'push' operation.

Calling the restore method is equivalent to taking a saved canvas state from the snapshot pool and restoring it on the canvas. It can also be called any number of times, which is equivalent to the pop-up operation.

Status includes

  1. Deformation, i.e. transformation matrix
  2. Clipping region
  3. Dash list
  4. Values of the following properties:
    strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, lineJoin, miterLimit, lineDashOffset, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation, font, textAlign, textBaseline, direction, imageSmoothingEnabled

For example:

var canvas=document.getElementById("myCanvas");
var ctx=canvas.getContext("2d");
//Default black
ctx.fillRect(0, 0, 50, 50); 
 //Save default state; 
//Set green
ctx.fillStyle = 'green'; 
ctx.fillRect(50, 50, 50, 50);
//Save green;
//Set red
ctx.fillStyle = 'red'; 
//Return to set green
ctx.fillRect(100, 100, 50, 50);
//Restore to default black
ctx.fillRect(150, 150, 50, 50);