Sunday, March 27, 2011

Tinting images in ImpactJs

For Creatures and Castles, I make a lot of use of tinting, as mentioned in the previous post. Now, I could take the lazy way out and just create a bunch of pre-tinted assets for the HTML5/Javascript version, but that's probably not the best way to go.

Instead I decided to dig into the way ImpactJS works and create a plugin that allows the developer to specify a tint color and alpha value on load.

To cut a long story short, I overrode the prototypes of init, load, and reload on the ig.Image class to allow me to specify an initial tint. At first I thought that overriding the init would be sufficient (I added optional tintColor and tintAlpha parameters). However, ImpactJs has inbuilt image caching that uses the path to the image file as the cache key. Consequently, the overrides of load and reload were also required to make sure that tinted images did not use the same cache key (I simply appended the tint color and alpha to the path to construct a new cache key).

The last piece of the puzzle was to override the ig.Loader end function to apply all of the specified tints to the image as they were loaded. Note that I used someone else's color conversion code; I left their attribution intact, of course.

The plugin code is as follows. Save this javascript file [UPDATED: See this post] in the lib/plugins directory. It's not quite perfect yet, but I'll come up with tweaks and usage examples next time.
Post a Comment