0
橢圓顏色順序(從左到右)應該是紅色,黃色,黑色,黃色和紅色。
這裏是代碼http://liveweave.com/Jq2xhrCanvas save()和restore()效果不佳
我的保存和恢復出了什麼問題?
橢圓顏色順序(從左到右)應該是紅色,黃色,黑色,黃色和紅色。
這裏是代碼http://liveweave.com/Jq2xhrCanvas save()和restore()效果不佳
我的保存和恢復出了什麼問題?
保存和恢復沒有出現問題。
問題在於,因爲您沒有爲每個弧使用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>
給予好評約'beginPath'良好的漁獲物。但請注意,'save'和'restore'是昂貴的操作,因爲它們保存並恢復上下文中的每個屬性 - 並且上下文具有許多屬性。一個更有效的計劃是將原始'fillStyle'保存在代碼片段頂部的一個變量('var originalFill = ctx.fillStyle')中,然後在代碼片段末尾重置fillStyle('ctx.fillStyle = originalFill' )。這消除了完全昂貴的保存/恢復。 ;-) – markE 2015-04-05 18:53:21