block by curran e199be2e4e6d16d8e34ed2d3cff76e9c

Cantor Set

Full Screen

The Cantor Set computed as an L-System and rendered using D3.

Built with blockbuilder.org

index.html

<!DOCTYPE html>
<head>
  <meta charset="utf-8">
  <script src="https://d3js.org/d3.v4.min.js"></script>
  <style> body { margin: 0 } </style>
</head>

<body>
  <svg width="960" height="500"></svg>
  <script>
    var rules = {
          A: "ABA",
          B: "BBB"
        },
        initialState = "A",
        iterations = 8,
        L = function(str){
          return str.split("").map(function (d){
            return rules[d];
          }).join("")
        },
        data = d3.range(iterations).map(function iterate(i){
          return i ? L(iterate(i - 1)) : initialState;
        });
    
    console.log(JSON.stringify(data, null, 2));
    // Prints the following:
    // [
    //   "A",
    //   "ABA",
    //   "ABABBBABA",
    //   "ABABBBABABBBBBBBBBABABBBABA",
    //   "ABABBBABABBBBBBBBBABABBBABABBBBBBBBBBBBBBBBBBBBBBBBBBBABABBBABABBBBBBBBBABABBBABA",
    //   "ABABBBABABBBBBBBBBABABBBABABBBBBBBBBBBBBBBBBBBBBBBBBBBABABBBABABBBBBBBBBABABBBABABBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBABABBBABABBBBBBBBBABABBBABABBBBBBBBBBBBBBBBBBBBBBBBBBBABABBBABABBBBBBBBBABABBBABA",
    //   ...
    
    var svg = d3.select("svg"),
        x = d3.scaleBand()
          .range([0, svg.attr("width")]),
        y = d3.scaleBand()
          .domain(d3.range(iterations))
          .rangeRound([0, svg.attr("height")]),
        rects = data
          .map(function(str, j){
            x.domain(d3.range(str.length));
            return str.split("")
              .map(function (symbol, i){
                return {
                  symbol: symbol,
                  x: x(i),
                  y: y(j),
                  width:  x.bandwidth(),
                  height: y.bandwidth()
                };
              })
              .filter(function (d){
                return d.symbol === "A";
              });
          })
          .reduce(function (a, b){
            return a.concat(b);
          }, []);
    
    svg.selectAll("rect").data(rects)
      .enter().append("rect")
        .attr("x",      function(d){ return d.x; })
        .attr("y",      function(d){ return d.y; })
        .attr("width",  function(d){ return d.width; })
        .attr("height", function(d){ return d.height; })
        .attr("fill", "black");
    
  </script>
</body>