天天看點

canvas restore 不能連續還原畫布的(rotate)、平移(translate)變換

今天遇到一個奇怪的問題,restore 隻能讀取一次狀态,也許是 save 的設計使然吧。

都說,canvas  restore 可以還原畫布旋轉( rotate )、平移( translate )變換,于是想畫一個旋轉對稱畫面就有了如下代碼:

<!DOCTYPE html>
<html><meta charset="utf-8" >
<body>
<canvas id="myCanvas" width="500" height="500" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script  language="JavaScript" type="text/javascript">
	var c=document.getElementById("myCanvas");
	var ctx=c.getContext("2d");
	ctx.translate(150,150);//為便于觀看效果,先将畫布平移一次
	ctx.save();//存儲狀态先
	for(let i=0;i<8;i++){
		ctx.fillStyle='#0066CC';
		ctx.translate(100,100);
		ctx.rotate(45*i*Math.PI/180);
		ctx.beginPath();
		ctx.moveTo(0,0);
		ctx.lineTo(20,100);
		ctx.lineTo(70,100);
		ctx.lineTo(0,0);
		ctx.closePath();
		ctx.fill();
		ctx.fillStyle="#ffffff";
		ctx.fillText(i+1,15,50);
		ctx.restore();//還原畫布
	}
	ctx.restore();
	ctx.fillStyle='#00f033';
	ctx.beginPath();
	ctx.moveTo(0,0);
	ctx.lineTo(0,10);
	ctx.lineTo(10,10);
	ctx.lineTo(0,0);
	ctx.closePath();
	ctx.fill();
</script> 
</body>
</html>
           

但是,得到的是這樣的效果:

canvas restore 不能連續還原畫布的(rotate)、平移(translate)變換

本來期望的是如下效果:

canvas restore 不能連續還原畫布的(rotate)、平移(translate)變換

可見,畫布的旋轉和平移經測試,隻能恢複一次 )用 restore 是無法連續恢複的:

<!DOCTYPE html>
<html><meta charset="utf-8" >
<body>
<canvas id="myCanvas" width="500" height="500" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script  language="JavaScript" type="text/javascript">
	var c=document.getElementById("myCanvas");
	var ctx=c.getContext("2d");
	ctx.translate(150,150);//為便于觀看效果,先将畫布平移一次
	ctx.save();//存儲狀态先
	for(let i=0;i<8;i++){
		ctx.fillStyle='#0066CC';
		ctx.translate(100,100);
		ctx.rotate(45*i*Math.PI/180);
		ctx.beginPath();
		ctx.moveTo(0,0);
		ctx.lineTo(20,100);
		ctx.lineTo(70,100);
		ctx.lineTo(0,0);
		ctx.closePath();
		ctx.fill();
		ctx.fillStyle="#ffffff";
		ctx.fillText(i+1,15,50);
		ctx.restore();
		ctx.save();//存儲狀态先
	}
	ctx.restore();
	ctx.fillStyle='#00f033';
	ctx.beginPath();
	ctx.moveTo(0,0);
	ctx.lineTo(0,10);
	ctx.lineTo(10,10);
	ctx.lineTo(0,0);
	ctx.closePath();
	ctx.fill();
</script> 
</body>
</html>