Fractal in JS

by Julien Roche

HTML

<canvas></canvas>

CSS

html, body {
  border: none;
  height: 100%;
  margin: 0px 0px 0px 0px;
  overflow: hidden;
  padding: 0px 0px 0px 0px;
  width: 100%;
}

Babel + JSX

let canvasElement = document.querySelector('canvas');
let context = canvasElement.getContext('2d');

const DEFAULT_ANGLE = -90;
const DEFAULT_DEPTH = 5;
 
context.fillStyle = '#000';
context.lineWidth = 1;
 
let deg_to_rad = Math.PI / 180.0;
 
function drawLine(x1, y1, x2, y2){
  context.beginPath();
  context.moveTo(x1, y1);
  context.lineTo(x2, y2);
    context.closePath();
  context.stroke();
}
 
function drawTree(x1, y1, depth = DEFAULT_DEPTH, angle = DEFAULT_ANGLE){
  if (depth !== 0){
    var x2 = x1 + (Math.cos(angle * deg_to_rad) * depth * 5.0);
    var y2 = y1 + (Math.sin(angle * deg_to_rad) * depth * 5.0);
    drawLine(x1, y1, x2, y2, depth);
    drawTree(x2, y2, depth - 1, angle - 20);
    drawTree(x2, y2, depth - 1, angle + 20);
  }
}
 
function draw() {
  drawTree(Math.round(canvasElement.width / 2), canvasElement.height);
}

function resize() {
  let { height, width } = document.body.getBoundingClientRect();
  canvasElement.height = height;
  canvasElement.width = width;

  draw();
}

window.addEventListener('resize', resize);
resize();