Last active
December 19, 2015 04:38
-
-
Save tenderlove/5898231 to your computer and use it in GitHub Desktop.
Sierpinski triangle with d3.js
This file contains hidden or 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="en"> | |
<head> | |
<meta charset="utf-8"> | |
<title>Sierpinski triangle</title> | |
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script> | |
</head> | |
<body> | |
<script type="text/javascript"> | |
//Width and height | |
var w = 500; | |
var h = 300; | |
var padding = 10; | |
var pointCount = 5000; // increase this to make more points | |
var xScale = d3.scale.linear() | |
.domain([0, w]) | |
.range([padding, w - padding]); | |
var yScale = d3.scale.linear() | |
.domain([0, w]) | |
.range([padding, w - padding]); | |
var dataset = [[w, h], [0, h], [w / 2, 0]]; | |
var triangle = dataset.slice(0); | |
//Create SVG element | |
var svg = d3.select("body") | |
.append("svg") | |
.attr("width", w) | |
.attr("height", h); | |
function draw(dataset) { | |
var circles = svg.selectAll("circle").data(dataset); | |
//Create circles | |
circles.enter() | |
.append("circle") | |
.attr("cx", function(d) { return xScale(d[0]); }) | |
.attr("cy", function(d) { return yScale(d[1]); }) | |
.attr("r", 1); | |
} | |
function genpoint(triangle, point) { | |
var vertex = triangle[Math.floor(Math.random() * triangle.length)]; | |
var x = (vertex[0] + point[0]) / 2; | |
var y = (vertex[1] + point[1]) / 2; | |
return [x, y]; | |
} | |
var point = [w / 2, h / 2]; | |
dataset.push(point); | |
for (var i = 0; i < pointCount; i++) { | |
point = genpoint(triangle, point); | |
dataset.push(point); | |
} | |
draw(dataset); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment