LoginSignup
9
8

More than 3 years have passed since last update.

Create.jsで親子関係のツリー図を描く

Last updated at Posted at 2020-02-28

概要

管理画面などで、既存のリストから親子関係のツリーを設定するUIを作ってみたくてやってみる。

有料のライブラリなどは見かけますが、使用料が高い・・・。
また、そこまで高機能なものは必要なかったりしたのでシンプルにする。

前提条件

HTML5のCanvasを操作するCreate.jsのライブラリを使っています。

ファイル構成

ローカルで動作確認したかったのでdocker使ってます。
※ Github: https://github.com/reflet/flowchart-create.js

ファイル構成
├ docker
│  └ nginx
│     └ default.conf
├ src
│  └ html
│    ├ flowchart.js    <- ツリー図を描くスクリプト
│    └ index.html      <- サンプルページ
│
└ docker-compose.yml

サンプルコード

サンプルページのコードはこんな感じです。
create.js に依存しているので、それはCDNで読み込んでます

src/html/index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>Create.js - フローチャート</title>
    <style type="text/css">
        body { margin: 0; padding: 0; }
        canvas { background: WhiteSmoke; }
    </style>
</head>
<body>
    <canvas id="myCanvas" width="1024" height="800"></canvas>

    <script src="https://code.createjs.com/1.0.0/createjs.min.js"></script>
    <script src="flowchart.js"></script>
    <script>
        window.addEventListener("load", function(){
            var flowchart = new FlowChart('myCanvas');

            // 初期化 (初期データ)
            flowchart.init('佐藤家',[
              {label:'太郎', children:[]},
              ...
              {label: '花子', children: [
                {label: '奈々子', children: []},
                {label: '八重子', children: []},
              ]},
            ]);
        });
    </script>
</body>
</html>

flowchart.js のコードについては、下記を参照ください。
https://github.com/reflet/flowchart-create.js/blob/master/src/html/flowchart.js

ローカル環境起動

実際に、ローカルブラウザで、動かしてみます。

$ git clone https://github.com/reflet/flowchart-create.js.git .
$ docker-compose up -d
$ open http://localhost:8080

こんな感じになりました。

sample.png

追加してみる

「+」ボタンを押して子要素を追加してみる。

add1.png

ラベルを入力し、OKボタンを押すと無事に追加されました。

add2.png

削除してみる

「✗」ボタンを押して削除してみる。

remove1.png

無事に削除されました。

remove2.png

まとめ

カンタンではありますが、とりあえずツリー図を作ることができました。

ドラッグしたり、好きな位置に配置したりもできましたが、
下記のような問題があるため、自動配置するようにしてそのような機能ははずしました。

  • 作ったツリーを再度表示する際に個別に座標情報を保存する必要がある
  • 重なり合わないようにする計算が面倒だった
  • 実際に操作すると複雑で意外と使い難くかった

以上です。

参考サイト

9
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
8