<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>save restore</title>
</head>
<body>
<canvas id="myCanvas" width="500" height="500" style="background-color: pink;"> 您的浏览器不支持canvas </canvas>
<script type="text/javascript">
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
// ctx.lineWidth = 10;
// ctx.strokeStyle = 'red';
// ctx.translate(canvas.width / 2, canvas.height / 2);
// ctx.rotate(0.5 * Math.PI);
// ctx.beginPath();
// ctx.moveTo(0, -180);
// ctx.lineTo(0, -250);
// ctx.stroke();
// // ctx.closePath();
// ctx.rotate(0.5 * Math.PI);
// ctx.beginPath();
// ctx.moveTo(0, -140);
// ctx.lineTo(0, -160);
// ctx.stroke();
// ctx.closePath();
// save: 用来保存canvas的状态, save之后可以调用 canvas 的平移 缩放 旋转等
// restore: 用来恢复 canvas 之前 保存的状态, 防止 save 后对 canvas 执行的操作有后续影响
// 对画布进行平移 旋转等操作其实是对整个canvas进行了平移旋转,如果不进行save & restore ,
// 则每一次绘画都是在上一次绘画的基础上进行操作,最后就会导致错位.
ctx.lineWidth = 10;
ctx.strokeStyle = 'red';
ctx.translate(canvas.width / 2, canvas.height / 2);
ctx.save();
ctx.rotate(0.5 * Math.PI);
ctx.beginPath();
ctx.moveTo(0, -180);
ctx.lineTo(0, -220);
ctx.stroke();
ctx.restore();
ctx.rotate(0.5 * Math.PI);
ctx.beginPath();
ctx.moveTo(0, -140);
ctx.lineTo(0, -160);
ctx.stroke();
</script>
</body>
</html>
上述运行结果: