简体   繁体   English

Javafx Canvas 矩形不画

[英]Javafx Canvas rect does not draw

i do something very basical and i just can't figure out what went wrong.我做了一些非常基本的事情,我就是不知道出了什么问题。

i try to draw a grid on a canvas, which seems straight forward, but i have problems with the outline of my rectangles.我尝试在 canvas 上绘制网格,这看起来很简单,但我的矩形轮廓有问题。 They simply are not drawn!!他们根本没有画!

    canvas.getGraphicsContext2D().setFill(Color.YELLOW);
    canvas.getGraphicsContext2D().setStroke(Color.BLACK);
    canvas.getGraphicsContext2D().setLineWidth(2d);

    for (int dy = 0; dy < height; dy ++){
        for (int dx = 0; dx < width; dx ++){
            canvas.getGraphicsContext2D().setFill(new Color( random.nextDouble(), random.nextDouble(), random.nextDouble() ,1));
            canvas.getGraphicsContext2D().fillRect(dx*32,dy*32,32,32);
            canvas.getGraphicsContext2D().rect(dx*32,dy*32,32,32);
        }
    }

the result is quite funny since it DOES draw, but not the outline...结果很有趣,因为它确实绘制了,但不是轮廓......

在此处输入图像描述

can't be that hard, can it?不可能那么难吧? what am i missing?我错过了什么?

You just append elements to the path, but you never do anything with it.您只需将 append 元素添加到路径中,但您永远不会对它做任何事情。 You need to invoke some method using the path.您需要使用路径调用一些方法。 In your case you need to call stroke :在您的情况下,您需要调用stroke

@Override
public void start(Stage stage) throws IOException {
    Canvas canvas = new Canvas(512, 512);
    Scene scene = new Scene(new Pane(canvas));

    Random random = new Random();
    final int height = 16;
    final int width = 16;

    GraphicsContext gc = canvas.getGraphicsContext2D();
    gc.setStroke(Color.BLACK);
    gc.setLineWidth(2d);

    for (int dy = 0; dy < height; dy++) {
        for (int dx = 0; dx < width; dx++) {
            gc.setFill(new Color(random.nextDouble(), random.nextDouble(), random.nextDouble(), 1));
            gc.fillRect(dx * 32, dy * 32, 32, 32);
            gc.rect(dx * 32, dy * 32, 32, 32);
        }
    }

    // draw the path we've constructed during the loop
    gc.stroke();

    stage.setScene(scene);
    stage.show();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM