Skip to content

Instantly share code, notes, and snippets.

@takatakamanbou
Last active June 29, 2019 07:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takatakamanbou/70ad58bc2c73a34cba3fbee14fb0a2b9 to your computer and use it in GitHub Desktop.
Save takatakamanbou/70ad58bc2c73a34cba3fbee14fb0a2b9 to your computer and use it in GitHub Desktop.
Graphics2019
import javafx.application.Application;
import javafx.stage.*; // Stage
import javafx.scene.*; // Scene
import javafx.scene.layout.*; // Pane, HBox
import javafx.scene.canvas.*; // Canvas, GraphicsContext
import javafx.scene.paint.*; // Color
import javafx.scene.image.*; // Image
import javafx.event.*; // MouseEvent
public class CanvasSample extends Application {
@Override
public void start(Stage pstage){
// Canvas オブジェクトを直接レイアウトコンテナに入れることもできるが,
// この例では Pane に入れて Pane を HBox に入れている
Pane pane1 = new Pane(); // Pane コンテナその1
Pane pane2 = new Pane(); // Pane コンテナその2
Pane pane3 = new Pane(); // Pane コンテナその3
Canvas canvas1 = new Canvas(200, 200); // 描画用 Canvas その1
Canvas canvas2 = new Canvas(200, 200); // 描画用 Canvas その2
Canvas canvas3 = new Canvas(200, 200); // 描画用 Canvas その3
pane1.getChildren().add(canvas1); // canvas1 を pane1 に載せる
pane2.getChildren().add(canvas2); // canvas2 を pane2 に載せる
pane3.getChildren().add(canvas3); // canvas3 を pane3 に載せる
HBox root = new HBox(pane1, pane2, pane3); // ルートノード
Scene scene = new Scene(root);
pstage.setTitle("CanvasSample");
pstage.setScene(scene);
pstage.show();
pane2.setStyle("-fx-background-color: #87CEEB;"); // 背景色を設定
drawFigures(canvas1); // canvas1 に描画
drawFigures2(canvas2); // canvas2 に描画
drawImages(canvas3); // canvas3 に描画
}
// 変数 c が表す Canvas 上に図形を描画
void drawFigures(Canvas c) {
// グラフィックスコンテクストを取得
GraphicsContext gc = c.getGraphicsContext2D();
gc.setStroke(Color.BLUE); // 線の色を設定
gc.setLineWidth(3); // 線の太さを設定
gc.strokeRect(30, 50, 100, 80); // 矩形
gc.setFill(Color.YELLOW); // 塗りつぶしの色を設定
gc.fillOval(80, 80, 100, 80); // 楕円
}
// 変数 c が表す Canvas 上に図形を描画 & イベント処理
void drawFigures2(Canvas c) {
GraphicsContext gc = c.getGraphicsContext2D();
gc.setFill(Color.BLUE);
// イベントハンドラを設定(ドラッグすると●を描く)
c.setOnMouseDragged((event) -> {
double x = event.getX(), y = event.getY();
gc.fillOval(x - 10, y - 10, 20, 20);
});
}
// 変数 c が表す Canvas 上に画像を表示 & イベント処理
void drawImages(Canvas c) {
GraphicsContext gc = c.getGraphicsContext2D();
Image img = new Image("blackuni.jpg");
// イベントハンドラを設定(クリックすると画像を描く)
c.setOnMouseClicked((event) -> {
double x = event.getX(), y = event.getY();
gc.drawImage(img, x - 20, y - 15, 40, 30);
});
}
public static void main(String[] args) {
launch(args);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment