1、坐标系和旋转是全局的
<style> canvas{ width: 500px; height: 300px; border: 1px solid; }</style></head><body><canvas id="can" width="500px" height="300px"></canvas><script> var canvas = document.getElementById("can"); var ctx = canvas.getContext("2d");// 坐标系和旋转是全局的,而不是对某一路径有作用 ctx.translate(100,100); ctx.rotate(Math.PI / 4); ctx.beginPath(); ctx.strokeRect(0,0,100,50); ctx.beginPath(); ctx.fillRect(200,0,100,50);</script></body>
2、restore和save:解决坐标轴问题
<style> canvas { width: 500px; height: 300px; border: 1px solid; }</style></head><body><canvas id="can" width="500px" height="300px"></canvas><script> var canvas = document.getElementById("can"); var ctx = canvas.getContext("2d"); ctx.save();//存储当前坐标平移和旋转状态;可保存坐标系的平移数据,缩放数据,旋转数据。 ctx.beginPath(); ctx.translate(100, 100); ctx.rotate(Math.PI / 4); ctx.strokeRect(0, 0, 100, 50); ctx.beginPath(); ctx.restore();// 恢复存储状态 ctx.translate(100, 100); ctx.fillRect(200, 0, 100, 50);</script></body>