Fire Spread

Click the link or highlight the code and copy it.  

Then, go to p5js.org and paste the code in the editor. 

Hit the "run" button, watch what happens. 

Make adjustments to the code, the hit the "run" button again. 

Repeat.  :) 

LINK TO WORKING CODE


CODE: 

const canvasWidth = 400;

const canvasHeight = 400;

const fireWidth = 80;

const fireHeight = 80;

const fireSpreadSpeed = 4;

const fireColorPalette = ['#070707', '#1F0707', '#2F0F07', '#470F07', '#571707', '#671F07', '#771F07', '#8F2707', '#9F2F07', '#AF3F07', '#BF4707', '#C74707', '#DF4F07', '#DF5707', '#DF5707', '#D75F07', '#D7670F', '#CF6F0F', '#CF770F', '#CF7F0F', '#CF8717', '#C78717', '#C78F17', '#C7971F', '#BF9F1F', '#BF9F1F', '#BFA727', '#BFA727', '#BFAF2F', '#B7AF2F', '#B7B72F', '#B7B737', '#CFCF6F', '#DFDF9F', '#EFEFC7', '#FFFFFF'];


let firePixels = [];


function setup() {

  createCanvas(canvasWidth, canvasHeight);

  initializeFirePixels();

  frameRate(30);

}


function draw() {

  background(0);

  updateFirePixels();

  renderFire();

}


function initializeFirePixels() {

  for (let row = 0; row < fireHeight; row++) {

    firePixels[row] = [];

    for (let col = 0; col < fireWidth; col++) {

      if (row === fireHeight - 1) {

        firePixels[row][col] = 36; // set the bottom row to the maximum intensity (36)

      } else {

        firePixels[row][col] = 0;

      }

    }

  }

}


function updateFirePixels() {

  for (let row = 0; row < fireHeight - 1; row++) {

    for (let col = 0; col < fireWidth; col++) {

      spreadFire(row, col);

    }

  }

}


function spreadFire(row, col) {

  const belowPixel = row + 1;

  if (belowPixel >= fireHeight) {

    return;

  }


  const decay = random(1) < 0.55 ? 1 : 0;

  const belowIntensity = firePixels[belowPixel][col] - decay;

  const spread = Math.floor(random(fireSpreadSpeed));


  const newIntensity = belowIntensity - spread;

  firePixels[row][col - spread] = newIntensity < 0 ? 0 : newIntensity;

}


function renderFire() {

  for (let row = 0; row < fireHeight; row++) {

    for (let col = 0; col < fireWidth; col++) {

      let intensity = firePixels[row][col];

      if (intensity >= fireColorPalette.length) {

        intensity = fireColorPalette.length - 1;

      }

      const fireColor = color(fireColorPalette[intensity]);

      fill(fireColor);

      noStroke();

      rect(col * 5, row * 5, 5, 5);

    }

  }

}