Wednesday, June 1, 2016

18. Canvas

A Canvas of 400 by 400 is child of the Group node.


After setting the color to red, four boundary rectangles and text are drawn on the canvas.


package ex18;

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.Stage;

public class Ex18 extends Application {
    
    @Override
    public void start(Stage primaryStage) {
        Group root = new Group();
        Scene scene = new Scene(root);
        primaryStage.setScene( scene );
        
        Canvas canvas = new Canvas( 400, 400 );
        root.getChildren().add( canvas );
        
        GraphicsContext gc = canvas.getGraphicsContext2D();
        
        gc.setFill( Color.RED );
        gc.fillRect(0, 0, 400, 10);
        gc.fillRect(0, 390, 400, 10);
        gc.fillRect(0, 10, 10, 390);
        gc.fillRect(390, 10, 10, 390);
        Font font = Font.font( "Georgia", 72 );
        gc.setFont(font);
        gc.fillText( "Hello,\nCanvas\nWorld!", 100, 100 );
        
        primaryStage.setTitle("Example 18. Canvas");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

This is the output:


No comments:

Post a Comment