To create easy animations in the JavaFX Canvas class, you can use the AnimationTimer class and the GraphicsContext class to update and draw the elements of the animation on the canvas at a fixed frame rate.
Here is an example of how you can create a simple animation in the Canvas class using an AnimationTimer:
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class AnimationExample extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
Canvas canvas = new Canvas(400, 400);
GraphicsContext gc = canvas.getGraphicsContext2D();
AnimationTimer timer = new AnimationTimer() {
double x = 0;
double y = 0;
double dx = 2;
double dy = 2;
@Override
public void handle(long now) {
gc.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
gc.fillOval(x, y, 50, 50);
x += dx;
y += dy;
if (x > canvas.getWidth() || x < 0) {
dx *= -1;
}
if (y > canvas.getHeight() || y < 0) {
dy *= -1;
}
}
};
StackPane root = new StackPane(canvas);
Scene scene = new Scene(root, 400, 400);
primaryStage.setScene(scene);
primaryStage.show();
timer.start();
}
}