我在寫一個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();
}
這適用於垂直方向的跑道,但我有一個水平跑道和線沒有被繪製。這是正在繪製的內容:
您會注意到我有一些代碼來檢查跑道名稱是否爲25
。這是我的水平跑道。控制檯輸出的值是我測試的兩個y值是292.5,這是合理的,它們應該是相同的,看起來像是一條水平線。如果我更改這些控制檯日誌行以輸出關聯的x值,則我會得到跑道x值的313
和航點的395.5
。再次,這是正確的。
爲什麼我不能從(313,292.5)到(395.5,292.5)畫一條線?
你可以創建一個JSFiddle嗎? – qxz