原文:http://tutorials.jenkov.com/html5-canvas/state.html
当使用2D Context在canvas上绘图时,2D context其实是某种状态,通过操作 2D Context的属性来设置这种状态,比如fillStyle和strokeStyle.所有这些操作总称为 2D context state.
通常,当在绘图时,你需要不断改变 2D context的状态。例如在画一条线或者矩形可能需要用到 strokeStyle,画其他线条或者矩形也需要用到strokeStyle,但是这次的值可能和前面用的不一样。这样的情况也可能出现在其他的状态里,比如 rotation,或者其他一些属性。
因为没画形状之前,设置所有的属性是非常繁琐的事,所有你可以将状态添加到状态栈里。通过这个状态栈,之前的状态就可以回滚。这样你就能够在当前状态改变的情况下很方便地返回到之前的保存的任何状态。
你添加和弹出2D context 状态使用的2个方法如下:
context.save(); // state pushed onto stack.
context.restore(); // state popped from stack, and set on 2D Context.
用来保存状态的栈,你能够给它添加任意次状态,之后可以弹出他们使用。这是个代码例子:
var canvas = document.getElementById("ex1");
var context = canvas.getContext("2d");
context.fillStyle ="#66ff66";
context.strokeStyle="#990000";
context.lineWidth = 5;
context.fillRect (5, 5, 50, 50);
context.strokeRect(5, 5, 50, 50);
context.save();
context.fillStyle = "#6666ff";
context.fillRect (65, 5, 50, 50);
context.strokeRect(65, 5, 50, 50);
context.save();
context.strokeStyle = "#000099";
context.fillRect (125, 5, 50, 50);
context.strokeRect(125, 5, 50, 50);
context.restore();
context.fillRect (185, 5, 50, 50);
context.strokeRect(185, 5, 50, 50);
context.restore();
context.fillRect (245, 5, 50, 50);
context.strokeRect(245, 5, 50, 50);
这是上边代码运行结果:

state stack 使用案例:
如果你改变了canvas的组成模式,或者变形的设置并且需要返回到变化之前的某个状态,这时状态栈是非常有用的。通过保存和恢复的组成模式或变形设置,你就可以很确信那就是正确的重置。否则 你可能不那么轻易地返回到你之前设置的状态。
2D context状态包括那些属性呢?
所有的2D context属性都可以被保存和被恢复。但是画在canvas上的东西是不行的。也就是说当保存了状态时,你没有保存所画区域的本身。你仅仅保存了2D context的设置集合(属性值)。所有设置包括:
- fillStyle
- font
- globalAlpha
- globalCompositionOperation
- lineCap
- lineJoin
- lineWidth
- miterLimit
- shadowBlur
- shadowColor
- shadowOffsetX
- shadowOffsetY
- strokeStyle
- textAlign
- textBaseline
- The clipping region
- The transformation matrix (rotations + translations via
context.rotate()+context.setTransform())
本文介绍了如何利用HTML5 Canvas的2DContext状态管理功能,通过保存和恢复状态,简化绘图过程中的状态切换,避免频繁修改属性带来的繁琐性。演示了如何使用context.save()和context.restore()方法来实现状态的保存和恢复,并提供了实例代码以供参考。

579

被折叠的 条评论
为什么被折叠?



