The moving is not working it only moves 1 time. And when I move image then there are 2 images there. How to do this?
GraphicsContext gc = canvas.getGraphicsContext2D();
Image img1 = new Image( "com/resources/aqua.jpg" );
gc.drawImage( img1, 0, 0, 50, 50 );
theScene.setOnKeyPressed((event) -> {
if (event.getCode() == KeyCode.RIGHT ){
gc.drawImage( img1, 50, 0, 50, 50 );
}
});
The Canvas
isn't cleared if you draw a new image. You have to do this "manually" using clearRect
, e.g.:
private double minX;
private double minY;
private double width;
private double height;
private GraphicsContext gc;
private Image img1;
private void drawImage() {
gc.drawImage(img1, minX, minY, width, height);
}
private void moveImage() {
gc.clearRect(minX, minY, width, height);
minX += 50;
drawImage();
}
...
this.gc = canvas.getGraphicsContext2D();
this.img1 = ...;
this.minX = 0;
this.minY = 0;
this.width = 50;
this.height = 50;
this.drawImage();
theScene.setOnKeyPressed((event) -> {
if (event.getCode() == KeyCode.RIGHT) {
moveImage();
}
});