2016-04-14 79 views
0

我使用頂部具有文本的矩形繪製兩個底紋。 正如你所看到的,我使用相同的循環得到了兩個不同的結果。 第一個「按鈕」在文本框後面隱藏文本。 第二個文字寫在上面。 這是爲什麼?排序如何在畫布中工作?在畫布上對對象排序

<body> 
    <canvas id="canvas" width="320" height="512" 
    style="position: absolute; left: 500px; top: 50px; z-index: 1;"></canvas> 
<script> 
var canvas = document.getElementById('canvas'); 
var context = canvas.getContext("2d"); 
canvas.style.backgroundColor = 'rgba(0, 0, 0, 0)'; 
context.clearRect(0, 0, 320, 16); 
gameMenu(); 

function gameMenu(){ 
var buttons = [ {x: 210, y: 420, w: 80, h: 30, s: "Messages"}, 
       {x: 210, y: 470, w: 80, h: 30, s: "Pause"} ], i = 0, r; 

    while(r = buttons[i++]) { 
    context.rect(r.x, r.y, r.w, r.h); 
    context.fillStyle = "rgb(26,26,26)"; 
    context.fill(); 

    context.fillStyle = 'White'; 
    context.font = "16px Tahoma"; 
    context.fillText(r.s, r.x + 18, r.y + 22); 
    } 
} 
</script> 
</body> 

這裏是一個JS小提琴: https://jsfiddle.net/oa84Lsxn/1/

+1

有沒有排序,你會需要繪製的對象以正確的順序,從下向上。 – Cyclonecode

+0

@Cyclone。好消息,但提問者有一個不同的問題。 ;-) – markE

回答

0

您必須開始每個新路徑操作(==每個新.rect)與context.beginPath。否則,所有先前的.rects將與當前的.rect一起重繪。

您的問題是,所有以前的路徑都與新路徑一起重繪。這意味着您的第一個矩形會與您的新第二矩形一起重繪 - 導致第一個矩形的文本被第一個矩形覆蓋。

以下是您的代碼的工作版本,其中添加了context.beginPath

var canvas=document.getElementById("canvas"); 
 
var context = canvas.getContext("2d"); 
 
canvas.style.backgroundColor = 'rgba(0, 0, 0, 0)'; 
 
context.clearRect(0, 0, 320, 16); 
 
gameMenu(); 
 

 
function gameMenu(){ 
 
// x,y changed to fit demo on StackSnipped window 
 
var buttons = [ {x: 40, y: 20, w: 80, h: 30, s: "Messages"}, 
 
       {x: 40, y: 70, w: 80, h: 30, s: "Pause"} ], 
 
       i = 0, r; 
 

 
    while(r = buttons[i++]) { 
 
     context.beginPath(); 
 
     context.rect(r.x, r.y, r.w, r.h); 
 
     context.fillStyle = "rgb(26,26,26)"; 
 
     context.fill(); 
 

 
     context.fillStyle = 'White'; 
 
     context.font = "16px Tahoma"; 
 
     context.fillText(r.s, r.x + 18, r.y + 22); 
 
    } 
 

 
}
#canvas{border:1px solid red; margin:0 auto; }
<canvas id="canvas" width=300 height=300></canvas>

+1

非常感謝! :D 很好的解釋。 – Lloyd

+0

@Lloyd或者使用fillRect()代替rect()+ fill()。如果markE回答了問題,可隨意將其標記爲已接受。這將會結束這個問題,並給出答案,爲此付出一些努力。 – K3N

+0

對不起,我不知道如何關閉它。這是綠色的複選標記:) – Lloyd