2016-04-14 60 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