javafx在Canvas上填充10个不同颜色的圆。位置、大小和颜色随机。
时间: 2023-05-15 16:05:24 浏览: 181
随机颜色、大小和位置的多边形画法
以下是JavaFX在Canvas上填充10个不同颜色的圆的示例代码:
```java
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.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import java.util.Random;
public class Main extends Application {
private static final int CANVAS_WIDTH = 400;
private static final int CANVAS_HEIGHT = 400;
private static final int CIRCLE_RADIUS_MIN = 10;
private static final int CIRCLE_RADIUS_MAX = 50;
private static final Random random = new Random();
@Override
public void start(Stage primaryStage) throws Exception {
Canvas canvas = new Canvas(CANVAS_WIDTH, CANVAS_HEIGHT);
GraphicsContext gc = canvas.getGraphicsContext2D();
for (int i = 0; i < 10; i++) {
double x = random.nextDouble() * CANVAS_WIDTH;
double y = random.nextDouble() * CANVAS_HEIGHT;
double radius = CIRCLE_RADIUS_MIN + random.nextDouble() * (CIRCLE_RADIUS_MAX - CIRCLE_RADIUS_MIN);
Color color = Color.rgb(random.nextInt(256), random.nextInt(256), random.nextInt(256));
gc.setFill(color);
gc.fillOval(x - radius, y - radius, radius * 2, radius * 2);
}
StackPane root = new StackPane(canvas);
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
```
这段代码使用JavaFX的Canvas和GraphicsContext类来绘制10个随机位置、大小和颜色的圆形。每个圆形的位置、半径和颜色都是随机生成的。
阅读全文