Javascript画布 - 绘制线条不绘图

时间:2016-11-21 00:08:54

标签: javascript canvas

我正在编写一个Javascript游戏。我有一个HTML画布,我正在使用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)划一条线?

1 个答案:

答案 0 :(得分:1)

对于最后一行,请使用.closePath()代替.fill()<?php /*for error 1045 config.inc.php*/ define("DB_HOST", "localhost"); define("DB_USER", "root"); define("DB_PASSWORD", ""); define("DB_DATABASE", "databasename"); $db = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE); if(mysqli_connect_errno()){ echo "database failed to connect with following errors:". mysqli_connect_error(); die(); } require_once $_SERVER['DOCUMENT_ROOT'].'/ecommerce/config.php'; require_once BASEURL.'helpers/helpers.php';

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

相关问题