forked from curran's block: Tree Fractal with SVG (broken). just added exit() method
Last active
September 13, 2019 09:18
-
-
Save LuisSevillano/d57b5c1cb3a4dcd72e52a29ceea340eb to your computer and use it in GitHub Desktop.
Tree Fractal with SVG
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
license: mit | |
border: no | |
height: 500 |
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> | |
<head> | |
<meta charset="utf-8"> | |
<title>fractal</title> | |
<script src="https://d3js.org/d3.v4.min.js"></script> | |
</head> | |
<body> | |
<svg width="960" height="500"></svg> | |
<script> | |
var svg = d3.select("svg"), | |
width = svg.attr("width"), | |
height = svg.attr("height"), | |
nMax = 95, | |
mouseX = 800, mouseY = 83, | |
scaleFactor = (100 - 4.4688) / 100; | |
function redraw (){ | |
var scale = 20, | |
angle = -mouseY / height * Math.PI / 8, | |
n = Math.floor(nMax * mouseX / 960), | |
up = Math.PI, | |
data = fractal(497, 472, up, scale, angle, 0, n, false); | |
render(data); | |
} | |
function fractal(x, y, direction, scale, angle, i, n, flip){ | |
var circle = { | |
x: x, | |
y: y, | |
radius: scale / 2 | |
}; | |
direction += angle; | |
x += Math.sin(direction) * scale; | |
y += Math.cos(direction) * scale; | |
if(flip){ | |
angle = -angle; | |
} | |
if(i < n){ | |
return [circle] | |
.concat( | |
fractal(x, y, direction, scale * scaleFactor, angle, i+1, n, flip) | |
) | |
.concat( | |
(i % 11 === 0) | |
? fractal(x, y, direction, scale * scaleFactor, angle, i+1, n, !flip) | |
: [] | |
); | |
} else { | |
return [circle]; | |
} | |
} | |
function render(data){ | |
var circles = svg.selectAll("circle").data(data); | |
circles | |
.enter() | |
.append("circle") | |
.merge(circles) | |
.attr("cx", function (d){ return d.x; }) | |
.attr("cy", function (d){ return d.y; }) | |
.attr("r", function (d){ return d.radius; }) | |
circles.exit().remove() | |
} | |
redraw(); | |
document.addEventListener("mousemove",function(e){ | |
mouseX = e.x; | |
mouseY = e.y; | |
redraw(); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment