JSFiddle - React, Tailwind, and code Playground

by alexb

HTML

<canvas></canvas>

CSS

canvas {
  position: absolute;
  height: 100%;
  width: 100%;
}

TypeScript

const NUM_LINES = 50;
const NUM_POINTS = 1000;

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

let H, W, mouseX, mouseY;

function setup() {
  canvas.height = window.innerHeight;
  canvas.width = window.innerWidth;
  H = canvas.height;
  W = canvas.width;
}

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

canvas.addEventListener('mousemove', function(e) {
	mouseX = e.offsetX;
  mouseY = e.offsetY;
}, false);

function draw() {
	ctx.clearRect(0, 0, W, H);
  
  for (let i = 0; i < NUM_LINES; i++) {
    ctx.beginPath();    
    for (let j = 0; j < NUM_POINTS + 1; j++) {
    	let x = W / NUM_POINTS * j;
    	let y = H / NUM_LINES * (i + 0.5);
      
      let dx = x - (mouseX || 0);
      let dy = y - (mouseY || 0);
      let d = dx*dx + dy*dy;
      
      x += 20000 / d * (dx / Math.abs(dx)) * 1;
      y += 20000 / d * (dy / Math.abs(dy)) * 1;
      
      if (j == 0) {
      	ctx.moveTo(x, y);
      }
      else {
      	ctx.lineTo(x, y);
      }
    }
    ctx.stroke();
  }
  
  requestAnimationFrame(draw);
}
requestAnimationFrame(draw);