canvas状态的保存与恢复
1. 状态的保存
save()
canvas状态存储在栈中,每当save()方法被调用后,当前的状态就被推送到栈中保存
1.1 绘画状态包括
1. 当前应用的变形(移动、旋转、缩放)
2. strokeStyle/fillStyle/globalAlpha/lineWidth/lineCap/lineJoin/miterLimit/shadowOffsetX/shadowOffsetY/shadowBlur/shadowColor/globalCompositeOperation的值
3. 当前裁切路径
可以调用任意多次save方法,即将多个绘画状态压栈
2. 状态的恢复
restore()
每次调用restore方法,上一个保存的状态就从栈中弹出,恢复该保存状态的设定
<!DOCTYPE html>
<html>
<head>
<title>Canvas</title>
</head>
<body>
<canvas id="canvas" width="800" height="600" style="border: solid 1px #24d1ec"></canvas>
<script>
function draw() {
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
//使用默认颜色填充矩形
ctx.fillRect(0 ,0, 150, 150);
ctx.save();//压栈1
//使用#ee5500颜色填充矩形
ctx.fillStyle = '#ee5500';
ctx.fillRect(15, 15, 120, 120);
ctx.save();//压栈1
//使用#33ffee颜色填充矩形
ctx.fillStyle = '#33ffee';
ctx.fillRect(30, 30, 90, 90);
//使用#ee5500颜色填充矩形
ctx.restore(); //弹栈1,此时fillStyle = '#ee5500'
ctx.fillRect(45, 45, 60, 60);
//使用默认颜色填充矩形
ctx.restore(); //弹栈2,此时fillStyle为默认值
ctx.fillRect(60, 60, 30, 30)
}
draw()
</script>
</body>
</html>