【问题标题】:Integrating both canvas and pane with Line objects in JavaFX将画布和窗格与 JavaFX 中的 Line 对象集成
【发布时间】:2020-11-23 23:58:08
【问题描述】:

免责声明:我正在使用 Java 和 Javafx 11。只是把它放在那里 :)

我正在尝试为Logo 创建解释器,但遇到了障碍。你看,我默认使用画布来显示我需要的所有东西,因为这适合我正在做的事情。但是,我没有考虑到我的 Turtle 需要移动。

private void drawTurtle() 
{
    vertices[0] = new Vector2(position.x, position.y + 15); // The three points that make the triangle that is the turtle
    vertices[1] = new Vector2(position.x - 15, position.y);
    vertices[2] = new Vector2(position.x + 15, position.y);
    
    vertices[1] = Renderer.rotatePoint(vertices[1], position, rotation); // applying rotation to vertices
    vertices[2] = Renderer.rotatePoint(vertices[2], position, rotation);
    vertices[0] = Renderer.rotatePoint(vertices[0], position, rotation);
    
    Renderer.drawLine(vertices[2], vertices[1], currentPen); // drawing the vertices
    Renderer.drawLine(vertices[2], vertices[0], currentPen);
    Renderer.drawLine(vertices[1], vertices[0], currentPen);
}

由于实时旋转海龟而留下的轨迹。

为了在不留下“痕迹”的情况下实现这一点,我尝试通过用白色笔在其上绘制来擦除现有的海龟。这给了我……奇怪的结果。

这是乌龟旋转360度后的样子。

然后我在这里看到一篇关于 SO 的帖子,其中谈到如果我想移动东西,我应该如何在窗格上使用 Line 对象。好吧,我尝试将它与画布结合起来制作 CanvasPane:

public class CanvasPane extends Pane
{
    public final Canvas canvas;

    public CanvasPane(double width, double height)
    {
        setWidth(width);
        setHeight(height);
        canvas = new Canvas(width, height);
        getChildren().add(canvas);

        canvas.widthProperty().bind(this.widthProperty()); // Change this so this canvas does not scale with the pane, and its size is constant.
        canvas.heightProperty().bind(this.heightProperty());
    }
}

并向其中添加了线对象,这样我就可以编辑它们的开始和结束值以使乌龟移动,但是我什么也没得到,没有线可以显示,而且我很困惑,不知道该做什么做。伟大的互联网上也没有任何帮助我,所以我现在问这个问题,看看是否有人对我如何完美地移动我的乌龟有想法。不,我不能使用clearRect()

TLDR:我的乌龟在画布上移动时留下痕迹,使用 Line and Pane 不起作用,我无法在画布上使用 clearRect()。救命!

【问题讨论】:

    标签: java javafx canvas line


    【解决方案1】:

    使用一个窗格来容纳画布节点和您的“乌龟”节点。

        Canvas canvas = new Canvas(640, 480);
        Shape turtle = new Polygon(); // fill in the points
        Pane p = new Pane(canvas, turtle);
    

    现在您可以通过设置布局坐标或应用平移来控制海龟节点的位置。由于它是最后添加的,它将被绘制在 Canvas 上。 (您也可以使用 StackPane 使分层更加明确。)

    【讨论】:

    • 嗯,这看起来可行!谢谢,我会试试看,如果可行,请标记接受此答案。
    猜你喜欢
    • 2016-10-14
    • 1970-01-01
    • 1970-01-01
    • 2018-12-14
    • 1970-01-01
    • 2014-09-17
    • 1970-01-01
    • 1970-01-01
    • 2020-08-04
    相关资源
    最近更新 更多