2016-11-21 97 views
1

我在写一个Javascript游戏时遇到问题。我有一个HTML画布,我正在用Javascript绘制。Javascript画布 - 画线不画图

我试图重新创建一个机场,所以我绘制了一些跑道(矩形),并绘制了一个从跑道到达端坐标量为x的航点(也是一个矩形)。我想画一条连接跑道和航点的线。

我的代码如下。请注意,我的跑道存储在Runway对象的数组中,其中topLeft是跑道的左上角,其中有x和y值,wayPointTopLeft是关联航点的左上角,也是x和y值, wayPointWidthHeight是我的航点矩形形状(绘制为方形)的宽度/高度。

for (i = 0; i < aRunways.length; i++) { 
     // Runway 
     ctx.fillStyle = clone(colourBrightGreen); 
     ctx.lineWidth=1; 
     ctx.rect(aRunways[i].topLeft.x,aRunways[i].topLeft.y,aRunways[i].width,aRunways[i].height); 
     ctx.fill(); 

     // Waypoint 
     if(aRunways[i].name == "25") { 
      console.log(aRunways[i].topLeft.y + (aRunways[i].height/2)); 
      console.log(aRunways[i].wayPointTopLeft.y + (aRunways[i].wayPointWidthHeight/2)); 
     } 

     ctx.rect(aRunways[i].wayPointTopLeft.x, aRunways[i].wayPointTopLeft.y, aRunways[i].wayPointWidthHeight, aRunways[i].wayPointWidthHeight); 
     ctx.strokeStyle = colourBrightGreen; 
     ctx.lineWidth=4; 
     ctx.stroke(); 

     // Name 
     var textX = 0; 
     var textY = 0; 

     ctx.font = "12px Arial";   
     textX = aRunways[i].wayPointTopLeft.x + (aRunways[i].wayPointWidthHeight/2) - (getTextWidth(aRunways[i].name, ctx.font)/2); 
     textY = (aRunways[i].wayPointTopLeft.y + aRunways[i].wayPointWidthHeight + 17); 
     ctx.fillStyle = clone(colourBrightGreen); 

     ctx.fillText(aRunways[i].name, textX, textY); 

     // Line 
     ctx.lineWidth = 1; 
     ctx.fillStyle = clone(colourBrightGreen); 
     ctx.beginPath(); 
     ctx.moveTo((aRunways[i].topLeft.x + (aRunways[i].width/2)), (aRunways[i].topLeft.y + (aRunways[i].height/2))); 
     ctx.lineTo((aRunways[i].wayPointTopLeft.x + (aRunways[i].wayPointWidthHeight/2)), (aRunways[i].wayPointTopLeft.y + (aRunways[i].wayPointWidthHeight/2))); 
     ctx.closePath(); 
     ctx.fill(); 
    } 

这适用于垂直方向的跑道,但我有一个水平跑道和线没有被绘制。这是正在绘制的内容: Output

您会注意到我有一些代码来检查跑道名称是否为25。这是我的水平跑道。控制台输出的值是我测试的两个y值是292.5,这是合理的,它们应该是相同的,看起来像是一条水平线。如果我更改这些控制台日志行以输出关联的x值,则我会得到跑道x值的313和航点的395.5。再次,这是正确的。

为什么我不能从(313,292.5)到(395.5,292.5)画一条线?

+0

你可以创建一个JSFiddle吗? – qxz

回答

1

为了您的最后一行,使用.stroke()代替.closePath().fill()

它看起来在这里就像你创建一个空的退化框,然后要求它填补,当你应该只画线。

+0

非常感谢。 –