Moving shapes in JavaFX canvas

2019-01-14 09:06发布

问题:

I would like to know if it's possible to use the GraphicsContext of a Canvas to create a circle(or any shape created with GraphicsContext) and then move it around on the canvas. If it is, what's the algorithm for doing so? I'm used to working with Java and I just can't figure it out.

Thanks in advance for any help.

回答1:

Basically, the way this works is that you setup a Canvas and update the location of the shape based on some Timeline. Then, in an AnimationTimer you paint your canvas.

import javafx.animation.*;
import javafx.application.Application;
import javafx.beans.property.*;
import javafx.scene.*;
import javafx.scene.canvas.*;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.Duration;

public class AnimatedCircleOnCanvas extends Application {
    public static final double W = 200; // canvas dimensions.
    public static final double H = 200;

    public static final double D = 20;  // diameter.

    @Override public void start(Stage stage) {
        DoubleProperty x  = new SimpleDoubleProperty();
        DoubleProperty y  = new SimpleDoubleProperty();

        Timeline timeline = new Timeline(
            new KeyFrame(Duration.seconds(0),
                    new KeyValue(x, 0),
                    new KeyValue(y, 0)
            ),
            new KeyFrame(Duration.seconds(3),
                    new KeyValue(x, W - D),
                    new KeyValue(y, H - D)
            )
        );
        timeline.setAutoReverse(true);
        timeline.setCycleCount(Timeline.INDEFINITE);

        final Canvas canvas = new Canvas(W, H);
        AnimationTimer timer = new AnimationTimer() {
            @Override
            public void handle(long now) {
                GraphicsContext gc = canvas.getGraphicsContext2D();
                gc.setFill(Color.CORNSILK);
                gc.fillRect(0, 0, W, H);
                gc.setFill(Color.FORESTGREEN);
                gc.fillOval(
                    x.doubleValue(),
                    y.doubleValue(),
                    D,
                    D
                );
            }
        };

        stage.setScene(
            new Scene(
                new Group(
                    canvas
                )
            )
        );
        stage.show();

        timer.start();
        timeline.play();
    }

    public static void main(String[] args) { launch(args); }
}  

It is however simpler to not use a Canvas, but instead use a Pane containing a Circle in combination with a TranslateTransition.