The last few weeks I’ve seen more fake burning fires then every other holiday season I can remember so when I noticed no one had written one in canvas I figured I’ll fill the gap.
Not being a game developer I needed to read a bit about how to create a reasonable but minimally resource intensive fire simulation. The one I chose works by randomly generating colors and then propagating them up the page while averaging out near by colors and adding a cooling effect.
The color palette takes the form of an array of colors ranging from yellow to orange to red. Canvas doesn’t have a standard way of setting colors directly and relies on css based colors when specifying for fills and paths. To address this I pre-generated all of the CSS RGB color strings to avoid the string concatination in the main loop.
In the Ruby implementation they used a single dimension array for tracking the current fire positions and colors. I changed this to use a 2 dimensional array because in my main animation loop I have to poll three reference points to calculate the new value for each square of the fire. Having a two dimensional array lets me store the row index and thus makes my look ups faster. Because this is getting called for every block of the fire map it made a big difference. I say square and not pixel because in this example I’m actually drawing squares so that I can change the scale of the fire if I want to. Next time I’ll probably try flipping the pixels directly using the Canvas ImageData method to see how much better it performs.
You’ll need to be using Chrome or a Firefox Beta for this to run correctly.