Skip to content
Advertisement

Accessing elements inside a GraphicsContext in JavaFX canvas

I’m implementing a simple hockey game following an MVC pattern. I’m having trouble refreshing the player’s position, which I have created inside a canvas using the GraphicsContext.drawImage() method. I’m inside an AnimationTimer anonymous class, inside the handle method.

The positions and boundaries are all reflected to the backend,so I don’t really need to do any particular logic here, I just want to refresh the player’s position on every frame, based on its position calculated inside the model, but I can’t access the image I’ve drawn before in any way. Here’s the code:

DefaultController controller;

@FXML
public void initialize() {
    
    controller = new DefaultController(800, 400);
    
    double playerX = controller.getField().getPlayer().getX();
    double playerY = controller.getField().getPlayer().getY();
    
    double enemyX = controller.getField().getEnemy().getX();
    double enemyY = controller.getField().getEnemy().getY();

    context.drawImage(new Image("player.png"),playerX, playerY);
    context.drawImage(new Image("enemy.png"),enemyX, enemyY);

    AnimationTimer timer = new AnimationTimer() {
        @Override
        public void handle(long now) {
            pane.getScene().addEventHandler(KeyEvent.KEY_PRESSED, (key) -> {
                if (key.getCode() == KeyCode.UP) {
                    controller.getField().getPlayer().setLocation(playerX,playerY-0.1)

                    // how do I update the player image position inside the canvas?
                }
            });
        }
    };
    timer.start();
}

Advertisement

Answer

You are following a completely wrong approach. You cannot update anything in a Canvas once it is drawn. You can just erase it and redraw it again. For what you are trying to do the scene graph is much better suited.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement