我们在canvas上绘制图形的时候,经常需要通过save()和restore()改变2D上下文的状态。举例来说,你在绘制直线或矩形的时候需要一种strokStyle,在绘制下一条直线或矩形的时候需要另一种strokStyle。又或者是不同的填充色,旋转角度等
当使用其2D上下文在html5画布上进行绘制时,该2D上下文处于某种状态。您可以通过操纵2D上下文 属性 (例如fillStyle 和)来设置该状态 stroke Style。所有这些操作总共称为2D上下文state。
通常,在画布上绘制时,您需要在绘制过程中更改2D上下文的状态。例如,strokStyle对于一条直线或矩形,可能需要 一个 ,而 stroke Style对于其他直线或矩形,则可能需要另 一个 。或其他轮换,或其他。
由于在绘制每个形状之前设置完整状态非常麻烦,因此可以将状态推送到状态堆栈上。然后可以从此状态堆栈中弹出较早的状态。这是在临时状态更改后恢复较早状态的 快速 方法 .
html5 Canvas画布状态示例
绘图状态进行压栈和出栈的 方法 如下:
context.save();?????//?将 一个 状态压入状态栈中. context.restore();??//?将最前面的状态出栈,并设置到2d上下文中.
被保存在堆栈中后,您可以将多个状态推送到该堆栈上,然后将其弹出。这是 一个 代码 示例:
示例
<canvas?id="ex1"?width="500"?height="100"?hljs-string">1px?solid?#cccccc;">HTML5?Canvas?not?supported</canvas> <script>var?canvas??=?document.getElementById("ex1");var?context?=?canvas.getContext("2d"); context.fillStyle??="#66ff66"; context. stroke ; context. linewidth ??=?5; context.fillRect??(5,?5,?50,?50); context. stroke Rect(5,?50); context.save(); context.fillStyle?=?"#6666ff"; context.fillRect??(65,?50); context. stroke Rect(65,?50); context.save(); context. stroke Style?=?"#000099"; context.fillRect??(125,?50); context. stroke Rect(125,?50); context.restore(); context.fillRect??(185,?50); context. stroke Rect(185,?50); context.restore(); context.fillRect??(245,?50); context. stroke Rect(245,?50); </script>
这是在画布上绘制时上述 代码 的结果:
状态栈的用处
如果您更改画布合成模式或转换设置,并且需要在进行更改之前先返回到设置,则状态堆栈非常有用。通过保存和恢复构图模式或转换设置,可以确保正确重置了它。否则,要返回到之前的确切设置可能会有些困难。
2D上下文的状态有哪些?
所有2D上下文 属性 都是保存和还原状态的一部分。但是,在画布上绘制的却不是。这意味着,在还原状态时,您不会还原绘图区域本身。您仅还原2D上下文设置( 属性 值)。这些设置 包括 :
fillStyle
font
globalAlpha
globalCompositio nop eration
lineCap
lineJoin
linewidth
miterLimit
shadowBlur
shadowColor
shadowOffsetX
shadowOffsetY
stroke Style
stroke Style
textAlign
textBaseline
The clipping region
The transformation matrix (通过context.rotate()+ 旋转+平移context.setTransform())
此列表并不详尽。
随着标准的发展,更多的 属性 可能成为2D上下文状态的一部分。
HTML5 Canvas toDataURL() ? ?HTML5 Canvas 合成