使用箭头移动图像 javafx
Move image javafx with arrows
移动不成功,只移动了1次。当我移动图像时,那里有 2 张图像。如何做到这一点?
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 );
}
});
如果您绘制新图像,Canvas
不会被清除。您必须使用 clearRect
执行此 "manually",例如:
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();
}
});
移动不成功,只移动了1次。当我移动图像时,那里有 2 张图像。如何做到这一点?
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 );
}
});
如果您绘制新图像,Canvas
不会被清除。您必须使用 clearRect
执行此 "manually",例如:
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();
}
});