Last active
March 19, 2017 08:55
-
-
Save pandanoir/91eb57a41e2bb731bdc78c865b03e084 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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