Particles

Particles flying around attractor.

by Nikita Sadkov

HTML

<p id="info">hello</p>
<canvas id="canvas" width="400" height="400" style="border:1px solid #000000;"></canvas>

JavaScript

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var cv_w = canvas.width;
var cv_h = canvas.height;

var info = document.getElementById('info');

var FPS = 30; //frames per seconds
var cols = 100;
var rows = 100;

var pal = [[0,0,0,0],[70,20,00,30],[100,0x5f,0x4f,0x70],
           [128,0xff,0x7f,0],[256,0xff,0xFF,0xFF]]
var colors = [];

for(j = 0; j < pal.length-1; j++) {
  var sp = pal[j];
  var ep = pal[j+1];
  for(i = sp[0]; i < ep[0]; i++) {
    var d = ep[0]-sp[0];
    var m = (i-sp[0])/d;
    var r = sp[1] + (ep[1]-sp[1])*m;
    var g = sp[2] + (ep[2]-sp[2])*m;
    var b = sp[3] + (ep[3]-sp[3])*m;
    //info.innerHTML = "Step: " +  j + "," + r;
    r = Math.min(r,255)&0xFFFFFF;
    g = Math.min(g,255)&0xFFFFFF;
    b = Math.min(b,255)&0xFFFFFF;
    colors[i] = "#" +
              r.toString(16).padStart(2, '0') +
              g.toString(16).padStart(2, '0') +
              b.toString(16).padStart(2, '0');
  }
}

var cell_w = cv_w/cols
var cell_h = cv_h/rows

var world0 = []
var world1 = []


for (y = -1; y < rows+1; y++) {
  world0[y] = [];
  world1[y] = [];
  for (x = -1; x < cols+1; x++) {
    world0[y][x] = 0;
    world1[y][x] = 0;
  }
}
world = world0;

var step = 0;

var nparticles = 3;
var particles = [];
var attractor = [cols/2,rows/2];
var gravity = 1;
var start_dist = (cols+rows)/2/2;

for (i = 0; i < nparticles; i++) {
  particles.push([attractor.slice(),[0,0]]);
}

function veq(a,b,e) {
  return Math.abs(a[0]-b[0])<e && Math.abs(a[1]-b[1])<e;
}
function vlen(a) {return Math.sqrt(a[0]*a[0] + a[1]*a[1]);}
function vunit(a) {
  var l = vlen(a);
  if (l == 0) return [0, 0];
  return [a[0]/l, a[1]/l];
}
function vadd(a,b) {return [a[0]+b[0], a[1]+b[1]];}
function vsub(a,b) {return [a[0]-b[0], a[1]-b[1]];}
function vmul(a,b) {return [a[0]*b, a[1]*b];}

function animate() {
  var x,y,z;
  world = step%2 == 0 ? world0 : world1;
  info.innerHTML = "Step: " + step;

  ctx.fillStyle = "#000000";
  ctx.fillRect(0, 0, cv_w,...