JSFiddle - React, Tailwind, and code Playground

by nima101

HTML

<canvas id="myCanvas" width="500" height="500" 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;
}

ps = gen_ngon(3, 300, 350, 250, -Math.PI/2);
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 = 0
}

function draw() {
//	w -= 0.0001;
	x += 0.005
	w = 0.5 + 0.5 / (1+Math.exp(20*x-5))
  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();

//	s = [400, 300];
  N = 40000
  sz = 1
  for (var i = 0; i < N; i++) {
    ctx.fillRect(s[0], s[1], sz, sz);
    px = ps[Math.floor(Math.random()*ps.length)];
    s = [w*s[0] + (1-w)*px[0], w*s[1] + (1-w)*px[1]];
  }
  if (w < 0.50001) {
  	x = 0;
  }
  window.requestAnimationFrame(draw);
  sleep(1);
}

init();

console.log('done');