fat*_*m91 10 animation javafx canvas
我想知道是否可以使用Canvas的GraphicsContext创建一个圆(或使用GraphicsContext创建的任何形状),然后在画布上移动它.如果是,那么这样做的算法是什么?我习惯使用Java,但我无法理解.
在此先感谢您的帮助.
jew*_*sea 26
基本上,它的工作方式是您设置Canvas并根据某些时间轴更新形状的位置.然后,在AnimationTimer中绘制画布.

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); }
}
Run Code Online (Sandbox Code Playgroud)
但是,不使用Canvas更简单,而是使用包含Circle和TranslateTransition的Pane.
| 归档时间: |
|
| 查看次数: |
22354 次 |
| 最近记录: |