JSFiddle - React, Tailwind, and code Playground

Pentagon fractal try

by greg gorlen

HTML

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

CSS

body {
  background: #111;
  width: 97vw;
  height: 97vh;
  overflow: hidden;
}

JavaScript

"use strict";

const canvas = document.getElementById("paper");
canvas.width = parseFloat(window.getComputedStyle(document.body).width);
canvas.height = parseFloat(window.getComputedStyle(document.body).height);
const ctx = canvas.getContext("2d");
const rad = deg => deg * Math.PI / 180; 
ctx.fillStyle = ctx.strokeStyle = "white";

const pentagon = (ctx, size, x, y, rotation) => {
  ctx.beginPath();
  
  for (let i = rotation; i <= 360 + rotation; i += 72) {
    ctx.lineTo(x + size * Math.cos(rad(i)),
               y + size * Math.sin(rad(i)));
  }
  
  ctx.stroke();
}

const render = function (ctx, size, x, y, count, rotation) {
  if (count > 0 && x > 0 && x < canvas.width && y > 0 && y < canvas.height) {
    pentagon(ctx, size, x, y, rotation);
    count -= 1;
    rotation += 36;
    size *= 0.4;
    
    for (let i = 0; i <= 360; i += 72) {
      render(ctx, size, 
             x + size * 2 * Math.cos(rad(i)), 
             y + size * 2 * Math.sin(rad(i)), count, rotation);
    }
  }
}
  

let x = canvas.width / 2;
let y = canvas.height / 2;
let size = 172;
let rotation = 0;

(function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  render(ctx, size, x, y, 5, rotation++);
  requestAnimationFrame(animate);
})();