Moving shapes in JavaFX canvas

后端 未结 1 1550
青春惊慌失措
青春惊慌失措 2020-12-03 05:41

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 ca

相关标签:
1条回答
  • 2020-12-03 06:13

    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.

    circlefun

    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.

    0 讨论(0)
提交回复
热议问题