在繪圖的過程中經常需要對環境進行設置,例如填充樣式、描邊,在操作完之後,往往需要恢復到原來的環境,CanvasRenderingContext2D中可以使用save和restore方法快速操作。
環境的保存和恢復還可以進行多層嵌套。多次使用save方法可以創建多個保存點,每次調用restore方法都會按save相反的順序獲取所保存的環境。
實例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<canvas id="c2d" width="600" height="600">瀏覽器不支持canvas</canvas>
<script>
const canvas = document.querySelector('#c2d');
if(canvas.getContext) {
const ctx = canvas.getContext('2d');
ctx.save();
ctx.fillStyle = 'red';
ctx.fillRect(0,0,100,100);
ctx.restore();
ctx.fillRect(100,100,100,100);
}
</script>
</body>
</html>