JSFiddle - React, Tailwind, and code Playground

by nima101

HTML

<canvas id="myCanvas" width="600" height="450" style="border:1px solid #000000;"></canvas>

JavaScript

function sleep(delay) {
    var start = new Date().getTime();
    while (new Date().getTime() < start + delay){}
}

function to_vec(p1, p2) {
	return [p2[0] - p1[0], p2[1] - p1[1]];
}

function tri_sample(p1, p2, p3) {
	a1 = Math.random();
  a2 = Math.random();
  if (a1 + a2 > 1) {
  	a1 = 1 - a1;
    a2 = 1 - a2;
  }
	v1 = to_vec(p1, p2);
	v2 = to_vec(p1, p3);
  
	return [p1[0] + v1[0]*a1 + v2[0]*a2, p1[1] + v1[1]*a1 + v2[1]*a2]
}

function gen_ngon(n, cx, cy, r, start_angle) {
	const angle = 2 * Math.PI / n;
  const points = [];
	for(var i = 0; i < n; ++i) {
    x = cx + r * Math.cos(i*angle + start_angle);
    y = cy + r * Math.sin(i*angle + start_angle);
    points.push([x, y]);
	}
  return points;
}

var ps = gen_ngon(3, 300, 300, 250, -Math.PI/2);
var s = tri_sample(ps[0], ps[1], ps[2]);
 
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

var w;
function init() {
   window.requestAnimationFrame(draw);
	 x = 1
}


function draw() {
	N = 2000
	if (x == 1) {
	  ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.beginPath();
    ctx.moveTo(...ps[0]);
    for (var i = 1; i < ps.length; i++) {
      ctx.lineTo(...ps[i]);
    }
    ctx.lineTo(...ps[0]);

    ctx.stroke();
  }

  sz = 3
	ctx.fillRect(s[0]-sz/2, s[1]-sz/2, sz, sz);
  px = ps[Math.floor(Math.random()*ps.length)];
  s = [0.5*s[0] + 0.5*px[0], 0.5*s[1] + 0.5*px[1]];

  window.requestAnimationFrame(draw);
	x += 1;
  if (x > N) {
	  x = 1;
  }
}

init();

console.log('done');