在 JavaFX 中将 canvas 和窗格与 Line 对象集成

Integrating both canvas and pane with Line objects in JavaFX

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

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

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 上遇到 post 讨论如果我想移动东西我应该如何在 Pane 上使用 Line 对象。好吧,我尝试将它与 canvas 结合起来制作 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:我的乌龟在 canvas 上移动时会留下痕迹,并且使用 Line 和 Pane 不起作用,我不能在我的 canvas 上使用 clearRect()。求助!

使用一个窗格同时容纳 Canvas 节点和您的“海龟”节点。

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

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