Fractal trees created with L-systems in d3.js
Used Daniel Shiffman's p5.js video/code as a foundation
| <!doctype html> | |
| <html> | |
| <body> | |
| <script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script> | |
| <script> | |
| var w = window.innerWidth, | |
| h = window.innerHeight; | |
| var theta = -12 * Math.PI / 190, | |
| length = 29, | |
| x0 = w/2, | |
| y0 = h, | |
| t0 = Math.PI / 2.5; | |
| function tree(string) { | |
| var tree = [], | |
| root = { path: "M" + x0 + "," + y0, children: [] }, | |
| step = { x: x0, y: y0, t: t0, branch: root }; | |
| var instructions = { | |
| 'F': function() { | |
| step.x -= length * Math.cos(step.t); | |
| step.y -= length * Math.sin(step.t); | |
| step.branch.path += "L" + step.x + "," + step.y; | |
| }, | |
| '+': function() { | |
| step.t += theta; | |
| }, | |
| '-': function() { | |
| step.t -= theta; | |
| }, | |
| '[': function() { | |
| tree.push(step); | |
| step = Object.create(step); | |
| var branch = { path: "M" + step.x + "," + step.y, children: [] }; | |
| step.branch.children.push(branch); | |
| step.branch = branch; | |
| }, | |
| ']': function() { | |
| step = tree.pop(); | |
| } | |
| }; | |
| string.split('').forEach(function(a) { instructions[a](); }); | |
| return root; | |
| } | |
| var svg = d3.select("body").append("svg") | |
| .attr("width", w) | |
| .attr("height", h) | |
| .datum(tree(line(4, {"F": "F-[-F+F+F-FF]+[+FF-F-F-]"}, "F"))) | |
| .each(grow); | |
| function grow(d) { | |
| d3.select(this).append("path") | |
| .attr("stroke", "black") | |
| .attr("stroke-opacity", 0.45) | |
| .attr("stroke-width", function(d,i){i * Math.PI/38}) | |
| .attr("fill", "none") | |
| .attr("d", function(d) { return d.path; }); | |
| d3.select(this).selectAll("g") | |
| .data(d.children) | |
| .enter().append("g") | |
| .transition() | |
| .each("start", grow); | |
| } | |
| function line(n, rules, axiom) { | |
| if (n == 0){ | |
| return axiom; | |
| } else{ | |
| return line(--n, rules, axiom.replace(/./g, function(a) { return rules[a] || a; })); | |
| } | |
| } | |
| </script> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
