Skip to content

Instantly share code, notes, and snippets.

@pandanoir pandanoir/index.html

Last active Mar 19, 2017
Embed
What would you like to do?
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title></title>
<script src="https://unpkg.com/unitaryjs/dist/unitary.min.js"></script>
<script src="https://unpkg.com/unitaryjs/dist/canvas.min.js"></script>
<script>
// ここに表示したい木構造を記述してください
var Node = function(val) {
this.value = val;
this.children = [];
}
var tree = new Node(5);
var node1 = new Node(1), node2 = new Node(8);
node2.children = [new Node(6), new Node(9)];
node1.children = [null, new Node(3)];
tree.children = [node1, node2];
</script>
<script>
;(function() {
var canvas = new Canvas('canvas');
canvas.mode = 'normal';
var r = 10, edge = 20, width = 200, between = 10, n = 2;
var Point = Unitary.Point,
Circle = Unitary.Circle,
_Text = Unitary.Text,
Segment = Unitary.Segment;
var getDepth = (tree, depth = 1) => {
if (tree == null) return depth;
if (tree.children.length == 0) return depth;
return tree.children.reduce((max, subTree) => Math.max(max, getDepth(subTree, depth + 1)), 0);
}
var getCircle = function(tree, width, basePoint) {
if (tree == null) return [];
if (width == null) {
width = Math.pow(n, getDepth(tree) - 1) * (2 * r + between) - 2 * between;
}
if (basePoint == null) {
basePoint = new Point(width / n, r * 2);
}
var circles = [];
return [].concat.apply([], tree.children.map((subTree, index) => {
const res = getCircle(subTree, width / n, basePoint.move(width * (2 * index + 1 - n) / (2 * n), r + edge))
if (res.length > 0) return [new Segment(basePoint, basePoint.move(width * (2 * index + 1 - n) / (2 * n), r + edge))].concat(res);
return res;
})).concat(
new Circle(basePoint, r).setFillStyle('#fff'),
new _Text(tree.value, basePoint).setBaseline('middle').setAlign('center')
);
}
canvas.add(new Unitary.Group(getCircle(tree)));
canvas.draw();
})();
</script>
<style>
canvas {border: 2px solid #000}
</style>
</head>
<body>
<canvas id="canvas" height="200" width="200"></canvas>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.