JavaFX Canvas & GraphicsContext
This program shows how to create a JavaFX Canvas and draw in it using the GraphicsContext.
For more information about how to use the GraphicsContext consult the API Page for the JavaFX Canvas GraphicsContext
Main.java
package ceccs;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.StrokeLineCap;
import javafx.stage.Stage;
public class CanvasDemo extends Application {
public static void main(String[] args){
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
/**To draw on a canvas you need to use its Graphics Context.*/
Canvas cancan = new Canvas(600,300);
GraphicsContext gc = cancan.getGraphicsContext2D();
/**buttons to draw on canvas, each runs a method on gc which is of class GraphicsContext*/
Button b1 = new Button("Stroke Line 1");
b1.setOnAction( event -> {
gc.setStroke(Color.DARKMAGENTA);
gc.setLineWidth(4.5);
gc.setLineCap(StrokeLineCap.ROUND);
gc.strokeLine(100,30, 550,270);
});
Button b2 = new Button("Random Line");
b2.setOnAction( event -> {
gc.setStroke(new Color(Math.random(),Math.random(),Math.random(),1));
gc.setLineWidth(Math.random() * 9 + 1);
gc.setLineCap(StrokeLineCap.ROUND);
double randX1 = Math.random() * cancan.getWidth();
double randX2 = Math.random() * cancan.getWidth();
double randY1 = Math.random() * cancan.getHeight();
double randY2 = Math.random() * cancan.getHeight();
gc.strokeLine(randX1,randY1,randX2,randY2);
});
Button b3 = new Button("Make Background Purple");
b3.setOnAction( event -> {
gc.setFill(Color.PURPLE);
gc.fillRect(0,0, cancan.getWidth(), cancan.getHeight());
});
Button b4 = new Button("Clear");
b4.setOnAction( event -> {
gc.clearRect(0,0, cancan.getWidth(), cancan.getHeight());
});
/** layout */
VBox outerCol = new VBox();
HBox buttonRow = new HBox();
buttonRow.getChildren().addAll(b1,b2,b3,b4);
outerCol.getChildren().addAll(cancan, buttonRow);
Scene scn = new Scene(outerCol);
primaryStage.setScene(scn);
primaryStage.setTitle("JavaFX Canvas Demo");
primaryStage.setResizable(false);
primaryStage.show();
}
}