Search code examples
javascriptmathfractals

Drawing fractals in javascript?


I'm working on a 2d (for starters) fractal-project as a fun way to learn more about recursive funncitons. I'm looking for some function that outputs coordinates for a line-based fractal, based on some conditional rules. Something like the H Tree.

Is there a name for such a function/algorithm? Are there any simple generic implementations available to look at?


Solution

  • just for fun:

    var c = document.getElementById("cnv").getContext("2d");
    var f = Math.sqrt(2);
    
    function hor(x, y, len) {
      if(len < 1) return;
    
      c.beginPath();
      c.moveTo(x - len/2, y);
      c.lineTo(x + len/2, y);
      c.stroke();
    
      setTimeout(function() {
        ver(x - len/2, y, len/f);
        ver(x + len/2, y, len/f);
      }, 500);
    }
    
    function ver(x, y, len) {
      if(len < 1) return;
    
      c.beginPath();
      c.moveTo(x, y - len/2);
      c.lineTo(x, y + len/2);
      c.stroke();
    
      setTimeout(function() {
        hor(x, y - len/2, len/f);
        hor(x, y + len/2, len/f);
      }, 500);
    }
    
    hor(300, 90, 150)
    <canvas id="cnv" width="600" height="180" />