JavaFX Canvas getGraphicsContext2D()

PreviousNext

JavaFX Canvas getGraphicsContext2D() returns the GraphicsContext associated with this Canvas.

Syntax

The method getGraphicsContext2D() from Canvas is declared as:

public GraphicsContext getGraphicsContext2D()

Return

The method getGraphicsContext2D() returns the GraphicsContext associated with this Canvas

Example

The following code shows how to use JavaFX Canvas getGraphicsContext2D()

Example 1

import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;

public class Diagram {
    private double[] values;
    public final static String[] names = { "????", "??????", "????", "??????" };

    public Diagram(double[] values) {
        this.values = values;
    }/* w   ww   .  d   e  m o   2 s   .c    om  */

    public void draw(Canvas canvas) {
        if (values == null || values.length == 0) {
            return;
        }
        GraphicsContext gc = canvas.getGraphicsContext2D();
        gc.setFill(Color.GREEN);
        gc.fillOval(50, 50, canvas.getWidth() - 100, canvas.getHeight() - 100);
    }
}

Example 2

import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;

import java.util.ArrayList;
import java.util.List;

public class Simulation {
    private final List<SimulationObject> simulationObjects = new ArrayList<>();

    public void draw(Canvas canvas) {
        GraphicsContext context = canvas.getGraphicsContext2D();
        context.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
        for (SimulationObject simulationObject : simulationObjects) {
            simulationObject.draw(context);
        }//    w  ww  .  d  e  m   o 2    s .   c  om  
    }

    public void add(SimulationObject simulationObject) {
        simulationObjects.add(simulationObject);
    }

    public void step() {
        for (SimulationObject obj : simulationObjects) {
            obj.step();
        }
    }
}

Example 3

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class Main extends Application {

    @Override//    w  w w  .  d   e  m o 2   s  .  c  o m  
    public void start(Stage primaryStage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("/org/opticaline/tetris/sample.fxml"));
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(root, 300, 275));
        primaryStage.show();
        Canvas canvas = (Canvas) root.getChildrenUnmodifiable().get(0);
        GraphicsContext gc = canvas.getGraphicsContext2D();

        gc.setFill(Color.BLUE);
        gc.fillRect(75, 75, 100, 100);
    }

    public static void main(String[] args) {
        launch(args);
    }
}
PreviousNext

Related