【问题标题】:Javascript Canvas - Draw Line not drawingJavascript Canvas - 画线不画
【发布时间】:2016-11-21 08:13:58
【问题描述】:

我在编写一个 Javascript 游戏时遇到了问题。我有一个使用 Javascript 绘制的 HTML 画布。

我正在尝试重建一个机场,因此我绘制了一些跑道(矩形),还绘制了一个航路点(也是一个矩形),该航路点位于距离跑道到达端 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 值,我会得到 313 用于跑道的 x 值和 395.5 用于航路点。同样,这是正确的。

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

【问题讨论】:

  • 你能创建一个 JSFiddle 吗?

标签: javascript canvas


【解决方案1】:

对于最后一行,使用.stroke() 而不是.closePath().fill()

从这里看起来你正在创建一个退化的空盒子,然后要求填充它,而你应该只是画一条线。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-22
    • 2016-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-23
    相关资源
    最近更新 更多