【问题标题】:Sorting objects on canvas对画布上的对象进行排序
【发布时间】:2016-04-14 18:01:22
【问题描述】:

我使用顶部带有文本的矩形绘制了两个按钮。 如您所见,我使用相同的循环得到了两个不同的结果。 第一个“按钮”将文本隐藏在框后面。 第二个有文字写在上面。 为什么是这样?在画布中排序是如何工作的?

<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 Fiddle: https://jsfiddle.net/oa84Lsxn/1/

【问题讨论】:

  • 没有排序,您需要以正确的顺序从下到上绘制对象。
  • @Cyclone。很好的信息,但提问者有不同的问题。 ;-)

标签: javascript sorting canvas layer


【解决方案1】:

您必须以context.beginPath 开始每个新路径操作(==每个新的.rect)。否则所有以前的 .rect 将与当前的 .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; }
&lt;canvas id="canvas" width=300 height=300&gt;&lt;/canvas&gt;

【讨论】:

  • 非常感谢! :D 很好的解释。
  • @Lloyd 或者使用 fillRect() 而不是 rect() + fill()。如果 markE 回答了问题,请随时将其标记为已接受。这将关闭问题并为回答者提供一些努力。
  • 抱歉,我不知道如何关闭它。这是绿色的复选标记:)
猜你喜欢
  • 1970-01-01
  • 2013-12-05
  • 2011-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-07
  • 2018-02-13
  • 2019-11-24
相关资源
最近更新 更多