Source: Http://www.silverlightchina.net/html/HTML_5/study/2012/0326/14828.htmlsave () and restore () Method is an essential method for drawing complex graphics. They are used to save and restore the canvas state, without parameters. The Canvas state is saved as a heap (stack), and each time the Save method is called, the current state is pushed into the heap and saved. This state includes: current applied variants (i.e. move, rotate and scale, see below): Strokestyle, FillStyle, Globalalpha, linewidth
The Save () and restore () methods are essential for drawing complex graphics. They are used to save and restore the canvas state, without parameters.
The Canvas state is saved as a heap (stack), and each time the Save method is called, the current state is pushed into the heap and saved. This state includes: current applied variants (i.e. move, rotate and scale, see below):
Strokestyle, FillStyle, Globalalpha, LineWidth, LineCap, LineJoin, Miterlimit, Shadowoffsetx, Shadowoffsety, Shadowblur , Shadowcolor, value of globalcompositeoperation
You can call the Save method any number of times. Each time the restore method is called, the Last Saved state pops out of the heap and all settings are restored.
Give an example of save and restore application.
We try to use this example of a continuous rectangle to describe how the state heap of a canvas works.
The first step is to draw a senior square with the default settings and then save the state. Change the fill color to draw the second smaller white square shape, and then save the state again. Change the fill color again to draw a smaller blue quad. Then we call the Restore method to set back to the previous save state of the fillstyle= "white", that is, if you do not set a color value and then draw the smallest rectangle when it is added to the color of the whites.
Once we call restore, the last state in the State heap pops up and restores all settings. If we had not previously saved the state with Save, then we would need to manually change the settings to go back to the previous state, which is applicable for two or three properties, and once more, our code will skyrocket. In short, the restore method can be understood to restore all of its corresponding settings in the current save state to the previous state
Code:
<Script Type="Text/javascript" >
Window.onload=function () {
var ctx=document.getelementbyidx_x ("canvas"). GetContext ("2d");
Ctx.fillrect (10,10,150,150);
Ctx.save ();
ctx.fillstyle="White";
Ctx.fillrect (30,30,110,110);
Ctx.save ();
ctx.fillstyle="Blue";
Ctx.fillrect (50,50,70,70);
Ctx.restore (); //Return to the previous state, i.e. ctx.fillstyle= "white";
Ctx.save ();
Ctx.fillrect (70,70,30,30); //So there is no setting FillStyle when the color is white, pay attention to Oh! If you restore it after the white rectangle, the FillStyle is black.
Ctx.restore ();
}
</script> 402
HTML5 Canvas Save and restore method explained