Introducing Canvas Indexed Color

2018-08-29 update: This is an old post about how I created a thin indexed color API in front of HTML5 canvas. It wasn’t very usable or powerful, but it was a fun learning experience. Instead of reading the post, I recommend checking out Mark Ferrari’s breathtaking color cycling art from 90s adventure games.


White SVG Tiger

First, I converted the classic SVG tiger into a set of canvas drawing instructions using Professor Cloud’s conversion tool. The output looks like this. Each call to cvm.getColor() used to be a string literal.

Vim’s regex saved me from having to edit 100,000 lines of canvas instructions by hand to replace the color strings.

The demo uses Knockout for handling all the update/draw events as well as updating the URL hash. Check the source code and you’ll see that there isn’t a vast tangled nest of event wirings. Each time one of the colors in this ViewModel is changed, Knockout automatically triggers the canvas redraw and the updates the URL with the new palette. Conversely, if the URL is changed, the ViewModel will update itself with the new value. Knockout calls this a “two-way data binding”.

I replaced the aforementioned color strings with calls to cvm, which is a Knockout ViewModel (in this case, an object that holds all the color data). cvm is populated with the SVG tiger’s default colors.

ko.observableArray([
  { hex: ko.observable("#000000") },
  { hex: ko.observable("#323232") },
  // .... many more ....
  { hex: ko.observable("#ff727f") },
  { hex: ko.observable("#ffffff") }
]);

Play with the colors, then copy the URL and send your tiger to your friends. :]

Crazy tiger.

Please note, this is only a simulation of an indexed color palette. It is not a true, usable, indexed-color API for canvas (someday, maybe!).

The color picker is Farbtastic. If you’re interested in reading more about the history of indexed color, and a mind-blowing canvas demo, go here.