目录

Canvas States

HTML5 canvas提供了两种保存和恢复画布状态的重要方法。 画布绘制状态基本上是已应用的所有样式和变换的快照,包括以下内容 -

  • 转换,旋转和缩放等转换

  • 当前剪辑区域。

  • 以下属性的当前值 - strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, lineJoin, miterLimit, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation, font, textAlign, textBaseline.

每次调用save方法时,Canvas状态都存储在堆栈中,并且每次调用restore方法时都会从堆栈返回上次保存的状态。

Sr.No. 方法和描述
1

save()

此方法将当前状态推送到堆栈上。

2

restore()

此方法弹出堆栈上的顶级状态,将上下文恢复到该状态。

例子 (Example)

下面是一个简单的例子,它利用上面提到的方法来显示如何调用恢复,恢复原始状态,最后一个矩形再次用黑色绘制。

<!DOCTYPE HTML>
<html>
   <head>
      <style>
         #test {
            width: 100px;
            height:100px;
            margin: 0px auto;
         }
      </style>
      <script type = "text/javascript">
         function drawShape() {
            // get the canvas element using the DOM
            var canvas = document.getElementById('mycanvas');
            // Make sure we don't execute when canvas isn't supported
            if (canvas.getContext) {
               // use getContext to use the canvas for drawing
               var ctx = canvas.getContext('2d');
               //  draw a rectangle with default settings
               ctx.fillRect(0,0,150,150);
               //  Save the default state
               ctx.save();
               // Make changes to the settings
               ctx.fillStyle = '#66FFFF'
               ctx.fillRect( 15,15,120,120); 
               // Save the current state
               ctx.save();
               // Make the new changes to the settings
               ctx.fillStyle = '#993333'
               ctx.globalAlpha = 0.5;
               ctx.fillRect(30,30,90,90);
               // Restore previous state
               ctx.restore();
               // Draw a rectangle with restored settings
               ctx.fillRect(45,45,60,60);   
               // Restore original state
               ctx.restore();
               // Draw a rectangle with restored settings
               ctx.fillRect(40,40,90,90);  
            } else {
               alert('You need Safari or Firefox 1.5+ to see this demo.');
            }
         }
      </script>
   </head>
   <body id = "test" onload = "drawShape();">
      <canvas id = "mycanvas"></canvas>
   </body>
</html>

以上示例将产生以下结果 -

新页面打开
↑回到顶部↑
WIKI教程 @2018