Skip to content

Instantly share code, notes, and snippets.

@Gmousse
Created April 18, 2017 13:49
Show Gist options
  • Save Gmousse/e1db3d5439066d28f51c5bd5bbbdc0f3 to your computer and use it in GitHub Desktop.
Save Gmousse/e1db3d5439066d28f51c5bd5bbbdc0f3 to your computer and use it in GitHub Desktop.
D3.js natural tree generator
/*
The MIT License (MIT)
Copyright (c) 2017 Guillaume Mousnier
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
function randomSign() {
return Math.sign(Math.random() - 0.5);
}
function randomAngle(base) {
return Math.random() * base;
}
function degreesToRadian(angle) {
return angle * (Math.PI / 180);
}
function rotateLine(x, y, angle) {
const radAngle = degreesToRadian(angle);
const cos = Math.cos(radAngle);
const sin = Math.sin(radAngle);
return {
x: (x * cos) - (y * sin),
y: (x * sin) + (y * cos),
};
}
function computeEdge(generation, memory) {
const rotation = rotateLine(
0, (memory.len / generation),
randomAngle(80) * randomSign()
);
return {
x1: memory.x2,
x2: memory.x2 + rotation.x,
y1: memory.y2,
y2: memory.y2 - rotation.y,
width: memory.width / generation,
len: memory.len,
};
}
function computeEdges(edges, deepness, memory, generation = 1) {
const childrens = generation < deepness ?
parent => computeEdges(edges, deepness, parent, generation + 1) :
() => [];
return edges.reduce(
(grid) => {
const edge = computeEdge(generation, memory);
return [...grid, edge, ...childrens(edge)];
}, generation === 1 ? [memory] : []
);
}
function computeTree(deepness, edgesByNode, width, height, branchWidth = 10) {
const branchLength = width / deepness;
const trunc = {
x1: width / 2,
x2: width / 2,
y1: height,
y2: height - branchLength,
width: branchWidth,
len: branchLength,
};
return computeEdges(d3.range(0, edgesByNode), deepness, trunc);
}
/*
The MIT License (MIT)
Copyright (c) 2017 Guillaume Mousnier
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
function renderBranches(domTree) {
return domTree
.attr('x1', branch => branch.x1)
.attr('x2', branch => branch.x2)
.attr('y1', branch => branch.y1)
.attr('y2', branch => branch.y2)
.style('stroke', 'black')
.style('stroke-width', branch => `${branch.width}px`);
}
function renderLeafs(domTree) {
return domTree
.attr('cx', branch => branch.x2)
.attr('cy', branch => branch.y2)
.attr('r', branch => (branch.y1 - branch.y2) / 4)
.style('fill', () => `rgba(25, 145, 48, ${Math.random()})`);
}
function renderTree(dom, grid) {
const domTree = d3.select(dom);
const domBranches = domTree
.selectAll('line')
.data(grid)
.enter()
.append('line');
const domLeafs = domTree
.selectAll('circle')
.data(grid.slice(10, grid.length))
.enter()
.append('circle');
renderBranches(domBranches);
renderLeafs(domLeafs);
}
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
from livereload import Server
server = Server()
server.watch('./index.html')
server.watch('./d3-natural-tree.js')
server.serve(root='./', host='0.0.0.0')
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="./d3-tree-compute.js" charset="utf-8"></script>
<script src="./d3-tree-display.js" charset="utf-8"></script>
<style media="screen">
.forest {
display: flex;
flex-direction: row;
}
.tree {
overflow: visible;
}
.tree:nth-child(2n+2) {
margin-left: 1em;
margin-top: 1em;
}
</style>
<title></title>
</head>
<body>
<h1>Forest:</h1>
<div class="forest">
<svg id="tree" class="tree" width="150" height="400">
</svg>
<svg id="tree2" class="tree" width="150" height="400">
</svg>
<svg id="tree3" class="tree" width="150" height="400">
</svg>
</div>
</body>
<script type="text/javascript">
var t0 = performance.now();
var grid = computeTree(4, 9, 400, 400);
var t1 = performance.now();
renderTree('#tree', grid);
var t2 = performance.now();
renderTree('#tree2', grid);
renderTree('#tree3', grid);
console.log("Compute: " + (t1 - t0) + " milliseconds.")
console.log("Display: " + (t2 - t1) + " milliseconds.")
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment