在 JavaFX 画布中移动形状 [英] Moving shapes in JavaFX canvas

查看:31
本文介绍了在 JavaFX 画布中移动形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以使用 Canvas 的 GraphicsContext 创建一个圆形(或使用 GraphicsContext 创建的任何形状),然后在画布上移动它.如果是,那么这样做的算法是什么?我习惯于使用 Java,但我就是想不通.

在此先感谢您的帮助.

解决方案

基本上,它的工作方式是您设置一个 包含一个Circle 结合 TranslateTransition.>

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.

解决方案

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.

这篇关于在 JavaFX 画布中移动形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆