JSFiddle - React, Tailwind, and code Playground

by zeen

HTML

<script src="https://code.createjs.com/easeljs-0.8.2.min.js"></script>
<script src="https://cdn.jsdelivr.net/lodash/4/lodash.min.js"></script>
<canvas id="canvas"></canvas>

CSS

html, body {
  padding: 0;
  margin: 0;
}

body {
  background: black;
}

JavaScript

const canvasEl = document.getElementById('canvas');
const ctx = canvasEl.getContext('2d');

function resetCanvas() {
  canvasEl.width = window.innerWidth;
  canvasEl.height = window.innerHeight;
}

window.onresize = function () {
  resetCanvas();
};

function drawHex({cx, cy, radius, color = '#fff', border = 1, angle=0}) {
  if (angle !== 0) {
    ctx.translate(cx, cy);
    ctx.rotate(angle);
    ctx.translate(-cx, -cy);
  }
  
  // draw hexagon
  ctx.beginPath();
  
  let r = radius - border/2 - 1;
  
  // point A
  ctx.moveTo(cx + r, cy);
  let outerAngle = Math.PI;
  
  for (let i = 0; i < 5; i += 1) {
  	outerAngle -= Math.PI / 3;
    
    let x = cx + (-1 * r * Math.cos(outerAngle));
    let y = cy + (r * Math.sin(outerAngle));
    ctx.lineTo(x, y);
  }

  ctx.closePath();

	ctx.strokeStyle = color;
  ctx.lineWidth = border;
  ctx.stroke();
}

function nextColor(withAlpha = true) {
	let randomHue = _.random(190, 360);
  let randomSat = _.random(44 ,89);
  let randomLgt = _.random(19, 69);
	
  let alpha = 1;
  if (withAlpha) {
  	alpha = _.random(0.01, 0.03, true)
  }

  return createjs.Graphics.getHSL(randomHue, randomSat, randomLgt, alpha);
}

function buildGrid(width, height, radius) {
	let d = 2 * radius;
	
  let rows = Math.floor(height / d) + 1;
  
  let cols = Math.floor(width / d) + 1;
  cols += Math.ceil(cols * radius / d);
  
  const grid = [];
	
  for (let ri = 0; ri < rows; ri += 1) {
  	let hexY = ri * d;
    
    for (let ci = 0; ci < cols; ci += 1) {
    	let hexX = ci * d;
      
      grid.push({
      	x: hexX,
        y: hexY,
        cx: hexX + radius,
        cy: hexY + radius,
        col: ci,
        row: ri,
        color: nextColor(true),
        radius: radius,
        border: _.random(1, radius / 4)
      });
    }
  }
  
  return grid;
}

function configureGrid(grid = [], radius) {
	let r = Math.cos(Math.PI / 6) * radius;
  let radiusOffset = (radius - r) * 2;
  
  let step = Math.PI / 2;
  let curStep = 0;
  
	for(let i = 0; i <...