L-System

My implementation of the L-System after learning about it on the Coding Train - http://thecodingtrain.com

by Victor Ribeiro

HTML

<canvas id="canvas"></canvas>

CSS

html, body{
  height:100%;
  margin:0;
  padding:0;
}
canvas{
  display:block;
}

JavaScript

let s = document.createElement('script');
s.src = "https://www.youtube.com/iframe_api";
document.body.appendChild(s);

let d = document.createElement('div');
d.style.display = "none";
document.body.appendChild(d);

let player;
function onYouTubeIframeAPIReady() {
  player = new YT.Player(d, {
    height: '0',
    width: '0',
    videoId: 'xNN7iTA57jM',
    events: {
      'onReady': onPlayerReady
    }
  });
}

function onPlayerReady() {
  player.playVideo();
}

let canvas = document.getElementById("canvas");
canvas.width = w = innerWidth;
canvas.height = h = innerHeight;
let c = canvas.getContext("2d");
let l = 4, a = 25, inc = 0.05, r;

let rules = {
	axiom: "X",
	X: "F[-X][X]F[-X]+FX",
  F: "FF",
  actions: {
            'F': function(){
            		c.beginPath();
                c.moveTo(0,0);
                c.lineTo(0,-l);
                c.stroke();
                c.translate(0,-l);
            	},
            '[': function(){
            		c.save();
            	},
            ']': function(){
            		c.restore();
            	},
            '-': function(){
            		c.rotate(-a*Math.PI/180);
            	},
            '+': function(){
            		c.rotate(a*Math.PI/180);
            	},
            'X': function(){}
  					}
};

function iterator(n){
	r = rules.axiom;
	for(let i = 0, ei = n; i < ei; i++){
    let t = "";
  	for(let j = 0, ej = r.length; j < ej; j++){
    	if(rules[r[j]]){
      	t += rules[r[j]];
      }else{
      	t += r[j];
      }
    }
    r = t;
  }
}

function draw(){
	a += Math.sin(inc+=0.05)*0.02;
	c.clearRect(0,0,w,h);
  c.translate(w>>1,h);
  c.rotate(a*0.05-1.1);
	for(let i = 0, ei = r.length; i < ei; i++){
  	rules.actions[r[i]]();
  }
  c.resetTransform();
  window.requestAnimationFrame(draw);
}


iterator(5);
draw();