Fire

Cellular automata looking like fire.

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 fire_size = 1.5;
var FPS = 30; //frames per seconds
var cols = 20;
var rows = 20;

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;


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

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

  for (y = 0; y < rows; y++) {
    for (x = 0; x < cols; x++) {
      NW = world[y-1][x-1];
      N  = world[y-1][x];
      NE = world[y-1][x+1];
      W  = world[y][x-1];
      C  = world[y][x];
      E  = world[y][x+1];
      SW = world[y+1][x-1];
      S  = world[y+1][x];
      SE = world[y+1][x+1];
      neibs = N+NW+E+SE+S+SW+W+NW;
      var v = neibs/8;
      idx = Math.max(0,Math.min(255,Math.floor(v*255)));
      ctx.fillStyle = colors[idx];
      ctx.fillRect(x*cell_w, y*cell_h, cell_w, cell_h);
    }
  }

  // create next world state
  var dst = step%2 == 0 ?...