How do you put a picture on the canvas?



  • How do you put a picture on the canvas (png) so you can paint it over? If there's an example.



  • The following should be worked:

    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.image.Image;
    import javafx.scene.layout.VBox;
    import javafx.stage.Stage;
    

    public class Main extends Application {
    final static int CANVAS_WIDTH = 400;
    final static int CANVAS_HEIGHT = 400;

    Image bgImage;
    double bgX, bgY, bgW = 100.0, bgH = 100.0;
    
    @Override
    public void start(final Stage primaryStage) {
    
        final Canvas canvas = new Canvas(CANVAS_WIDTH, CANVAS_HEIGHT);
        final GraphicsContext graphicsContext = canvas.getGraphicsContext2D();
        initDraw(graphicsContext);
    
        Group root = new Group();
        VBox vBox = new VBox();
        vBox.getChildren().addAll(canvas);
        root.getChildren().add(vBox);
        Scene scene = new Scene(root, 400, 425);
        primaryStage.setTitle("image on canvas");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    
    
    private void initDraw(GraphicsContext gc){
        double canvasWidth = gc.getCanvas().getWidth();
        double canvasHeight = gc.getCanvas().getHeight();
    
        // достаем нужную картинку по какому-то пути.
        // в данном случае из папки с классами достаем accept.png
        bgImage = new Image(getClass().getResourceAsStream("accept.png"));
        bgX = canvasWidth/2 - bgW/2;
        bgY = canvasHeight/2 - bgH/2;
        gc.drawImage(bgImage, bgX, bgY, bgW, bgH);
    }
    
    
    public static void main(String[] args) {
        launch(args);
    }    
    

    }

    Create a scene, add a canva. Let's add a picture. graphicsContext♪ We get the picture from where it's convenient and comfortable. Here's the picture. accept.png It's right in a folder with a class file, and it'll be right downtown.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2