椭圆颜色顺序(从左到右)应该是红、黄、黑、黄、红。
这是代码http://liveweave.com/Jq2xhr
我的保存和恢复出了什么问题??
保存和恢复没有任何问题。
问题是,由于您没有为每个弧使用 beginPath,因此每次调用 fill() 时,您都会用新颜色重新填充弧。
你的第三个圆圈被填充为黑色,然后是黄色,最后又是红色。
这应该可以解决它。
/* Write JavaScript here */
var canvas=document.getElementById('m');
var ctx=canvas.getContext('2d');
//儲存canvas會存在Stack內。Stack特性是最後儲存的數值會最先顯示,所以如果呼叫restore方法,會顯示最近的描繪狀態,在呼叫一次的話就會顯示之前的狀態。//
ctx.beginPath();
ctx.fillStyle="red";
ctx.arc(80, 80, 50, 0, Math.PI*2, true);//arc(x,y,r,starAngle, endAngle, anticlockwise)
ctx.fill();
ctx.save();
ctx.beginPath();
ctx.fillStyle="yellow";
ctx.arc(210, 80, 50, 0, Math.PI*2, true);
ctx.fill();
ctx.save();
ctx.beginPath();
ctx.fillStyle="#000000";
ctx.arc(340, 80, 50, 0, Math.PI*2, true);
ctx.fill();
ctx.restore();
ctx.beginPath();
ctx.arc(470,80, 50, 0, Math.PI*2, true);
ctx.fill();
ctx.beginPath();
ctx.restore();
ctx.arc(600, 80, 50, 0, Math.PI*2, true);
ctx.fill();
<!DOCTYPE html>
<html>
<head>
<title>使用save和restore繪製圖形</title>
</head>
<body>
<!-- Start your code here -->
<p class="lw"></p>
<canvas id="m" width="1000" height="200"></canvas>
<!-- End your code here -->
</body>
</html>
如果它可以帮助其他人通过网络搜索登陆这里,请注意
ctx.restore()
的工作原理:
Canvas 2D API 的
ctx.restore()
方法通过弹出绘图状态堆栈中的顶部条目来恢复最近保存的画布状态。如果没有保存的状态,这个方法什么也不做。
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/restore
我犯的错误是假设我可以简单地ctx.save()
一次,然后通过单次保存多次
ctx.restore()
。但这(违反直觉)不是保存/恢复的工作原理。每次您调用
ctx.restore()
时,它都会“用完”保存,因此如果您想将来再次使用该保存,您需要在调用
ctx.save()
后立即调用
ctx.restore()
。因此,如果您的问题/误解与我的一样,那么您可以通过简单地更改此的所有实例来解决它:
ctx.restore();
对此:
ctx.restore();
ctx.save();