深入了解Canvas标签(5)——变形

来源:互联网 发布:linux手册下载 编辑:程序博客网 时间:2024/05/23 15:55

状态的保存和恢复

在了解变形之前,我先介绍一下两个你一旦开始绘制复杂图形就必不可少的方法。

  1. save()
  2. restore()
复制代码

save 和 restore 方法是用来保存和恢复 canvas 状态的,都没有参数。Canvas 的状态就是当前画面应用的所有样式和变形的一个快照。

Canvas 状态是以堆(stack)的方式保存的,每一次调用 save 方法,当前的状态就会被推入堆中保存起来。这种状态包括:
      当前应用的变形(即移动,旋转和缩放,见下)
      strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, lineJoin, miterLimit, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation 的值
      当前的裁切路径(clipping path),会在下一节介绍。

你可以调用任意多次 save 方法。

每一次调用 restore 方法,上一个保存的状态就从堆中弹出,所有设定都恢复。

save 和 restore 的应用例子
我们尝试用这个连续矩形的例子来描述 canvas 的状态堆是如何工作的。

第一步是用默认设置画一个大四方形,然后保存一下状态。改变填充颜色画第二个小一点的蓝色四方形,然后再保存一下状态。再次改变填充颜色绘制更小一点的半透明的白色四方形。

到目前为止所做的动作和前面章节的都很类似。不过一旦我们调用 restore,状态堆中最后的状态会弹出,并恢复所有设置。如果不是之前用 save 保存了状态,那么我们就需要手动改变设置来回到前一个状态,这个对于两三个属性的时候还是适用的,一旦多了,我们的代码将会猛涨。

当第二次调用 restore 时,已经恢复到最初的状态,因此最后是再一次绘制出一个黑色的四方形。


查看示例

  1. function draw() {
  2.   var ctx = document.getElementById('canvas').getContext('2d');
  3.   ctx.fillRect(0,0,150,150);  // Draw a rectangle with default settings
  4.   ctx.save();                  // Save the default state
  5.   ctx.fillStyle = '#09F'      // Make changes to the settings
  6.   ctx.fillRect(15,15,120,120); // Draw a rectangle with new settings
  7.   ctx.save();                  // Save the current state
  8.   ctx.fillStyle = '#FFF'      // Make changes to the settings
  9.   ctx.globalAlpha = 0.5;   
  10.   ctx.fillRect(30,30,90,90);  // Draw a rectangle with new settings
  11.   ctx.restore();              // Restore previous state
  12.   ctx.fillRect(45,45,60,60);  // Draw a rectangle with restored settings
  13.   ctx.restore();              // Restore original state
  14.   ctx.fillRect(60,60,30,30);  // Draw a rectangle with restored settings
  15. }
复制代码
原创粉丝点击