canvas-state+state stack

原文: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())
这个列表并不全,随着标准的推进,可能有更多的属性被加入2D context 。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值