在JavaFX画布中移动形状 [英] Moving shapes in JavaFX canvas
问题描述
我想知道是否可以使用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屋!