2015-04-05 102 views

回答

1

保存和恢复没有出现问题。
问题在于,因为您没有为每个弧使用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>

+0

给予好评约'beginPath'良好的渔获物。但请注意,'save'和'restore'是昂贵的操作,因为它们保存并恢复上下文中的每个属性 - 并且上下文具有许多属性。一个更有效的计划是将原始'fillStyle'保存在代码片段顶部的一个变量('var originalFill = ctx.fillStyle')中,然后在代码片段末尾重置fillStyle('ctx.fillStyle = originalFill' )。这消除了完全昂贵的保存/恢复。 ;-) – markE 2015-04-05 18:53:21