JSFiddle - React, Tailwind, and code Playground

by jcubed111

HTML

<canvas id='canvas' width='500' height='500'></canvas>

CSS

body{
    background:#EEE;
}
canvas{
    width:500px;
    height:500px;
    background:#FFF;
    border:1px solid #CCC;
}

JavaScript

//particles
var particles = [];


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


function rgb(r, g, b) {
    r=Math.round(r);
    g=Math.round(g);
    b=Math.round(b);
    return "rgba(" + r + "," + g + "," + b + ",1)";
}

function rgba(r, g, b, a) {
    r=Math.round(r);
    g=Math.round(g);
    b=Math.round(b);
    return "rgba(" + r + "," + g + "," + b + "," + a + ")";
}


function Particle(x, y, a, b) {
    this.x = x;
    this.y = y;
    this.xF = 0;
    this.yF = 0;
    this.a = a;
    this.b = b;
}


function dFromParticle(x, y, i) {
    return Math.sqrt(Math.pow(particles[i].x - x, 2) + Math.pow(particles[i].y - y, 2));
}

function attraction(d){return Math.pow(d,-1)-Math.pow(d,-2);};

/*************************************************************/

/*particles[0] = new Particle(250, 100, -1, -1); //K
particles[1] = new Particle(200, 250, -1, +1); //B
particles[2] = new Particle(150, 150, +1, -1); //R
particles[3] = new Particle(200, 200, +1, +1); //P
*/


for(i=0;i<100;i++){
    //particles[i] = new Particle(Math.random()*400+50, Math.random()*400+50, 1, Math.random()>.5?1:-1); // R P
    
    //particles[i] = new Particle(Math.random()*400+50, Math.random()*400+50, 1, 1); //P
    
    //a=Math.floor(Math.random()*3); particles[i] = new Particle(Math.random()*400+50, Math.random()*400+50, a!=0?1:-1, a==2?1:-1); // K R P
    
    a=Math.floor(Math.random()*3); particles[i] = new Particle(Math.random()*400+50, Math.random()*400+50, a!=0?1:-1, a!=1?1:-1); // B R P
}


function loop() {
    ctx.clearRect(0,0,500,500);
    
    //update particle velocities
    for (i = 0; i < particles.length; i++) {
        for (j = 0; j < particles.length; j++) {
            if(j!=i){
                a = particles[i].a*particles[j].a*attraction(dFromParticle(particles[i].x,particles[i].y,j));
                particles[i].xF+=(particles[j].x-particles[i].x)*a*.005;
                particles[i].yF+=(particles[j].y-particles[i].y)*a*.005;
            }
        }
  ...