<canvas id="canvas"></canvas>
body, html {
  margin: 0;
  overflow: hidden;
}

canvas {
  display: block;
  cursor: pointer;
}
/*
  Johan Karlsson, 2020
  https://twitter.com/DonKarlssonSan
  MIT License, see Details View
*/

let canvas;
let ctx;
let w, h;
let points;
let hueOffset;

function setup() {
  canvas = document.querySelector("#canvas");
  ctx = canvas.getContext("2d");
  resize();
  window.addEventListener("resize", () => {
    resize();
    draw();
  });
  canvas.addEventListener("click", draw);
}

function resize() {
  w = canvas.width = window.innerWidth;
  h = canvas.height = window.innerHeight;
}

function setupRandomPoints() {
  points = [];
  let nrOfPoints = w * h / 2000;
  let c = [w / 2, h / 2];
  for(let i = 0; i < nrOfPoints; i++) {
    let x = Math.random() * w;
    let y = Math.random() * h;
    points.push([x, y]);
  }
}

function dist(p1, p2) {
  return Math.hypot(p1[0] - p2[0], p1[1] - p2[1]);
}

function sortPointsClosestTo(p0) {
  points.sort((a, b) => dist(a, p0) - dist(b, p0));
}

function getClosestThreePoints(x, y) {
  sortPointsClosestTo([x, y]);
  let p1 = points[0];
  let p2 = points[1];
  let p3 = points[2];
  return [p1, p2, p3];
}

function setColorBasedOnX(x) {
  let hue = x / w * 360 + hueOffset;
  ctx.strokeStyle = `hsla(${hue}, 80%, 50%, 0.7)`;
  ctx.fillStyle = `hsla(${hue}, 80%, 50%, 0.4)`;
}

function drawTriangle(x, y) {
  let [p1, p2, p3] = getClosestThreePoints(x, y);
  
  setColorBasedOnX(x);
  ctx.beginPath();
  ctx.moveTo(p1[0], p1[1]);
  ctx.lineTo(p2[0], p2[1]);
  ctx.lineTo(p3[0], p3[1]);
  ctx.closePath();
  ctx.stroke();
  ctx.fill();
}

function drawTrianglePattern() {
  hueOffset = Math.random() * 360;
  let nrOfTriangles = w * h / 500;
  for(let i = 0; i < nrOfTriangles; i++) {
    let x = Math.random() * w;
    let y = Math.random() * h;
    drawTriangle(x, y);
  }
}

function draw() {
  ctx.fillStyle = "black";
  ctx.fillRect(0, 0, w, h);
  setupRandomPoints();
  drawTrianglePattern();
}

setup();
draw();
View Compiled

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.