Canvas中保存畫布狀態及還原

1.save();

 restore();

示例代碼:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>form測試</title>
    <style type="text/css">
        #can{
            background: pink;
        }
    </style>
</head>
<body>
  <canvas id="can" width="800px" height="600pxf"></canvas>
  <script type="text/javascript">
      var canvas=document.getElementById("can");
      var ctx=canvas.getContext("2d");
//      三角形
      ctx.beginPath();
      ctx.moveTo(100,50);
      ctx.lineTo(40,80);
      ctx.lineTo(120,100);
      ctx.closePath();
      ctx.lineWidth=10;
      ctx.fillStyle='yellow';
      ctx.strokeStyle="blue";
      ctx.fill();
      ctx.stroke();
//            ctx.beginPath();
      ctx.arc(300,300,100,30,270,false);
      ctx.closePath();
      ctx.fill();
//      矩形
      ctx.fillRect(500,300,100,100);

      ctx.fillStyle = "rgba(255,0,0,1)";    //給定畫筆顏色
      ctx.save();    //保存顏色
      ctx.beginPath();
      ctx.rect(300,300,110,110);
      ctx.fill();
      //新設置一下畫筆並作畫
      ctx.fillStyle = '#0f0';
      ctx.save();
      ctx.fillRect(300,400,111,111);
      ctx.fillStyle = 'blue';
      //還原到上次儲存的地方
      ctx.restore();
      ctx.restore();
      ctx.fillRect(300,500,111,111);   //再次繪製矩形,顏色爲restore後的顏色


  </script>
</body>
</html>
注意:save()和restore()操作可以多次使用,但是每一次restore只能還原到距離最近的一次,也就是後保存的先還原。

運行效果:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章