Adam Luptak

Javascript Color Blending

JavaScript
Aug. 24, 2013

Every front-end developer has probably written a custom color class. In fact, most have probably written as many color classes - if not more - as the languages they know.

While working on a feature of the upcoming Rally Interactive site (coming late 2013), I needed a flexible JavaScript color class. In addition to the usual RGB and HSV tools that I needed, I also would need the ability to blend or transition from one color to another.

Color transitions are a tricky thing. Simple tweens in the RGB color-space sometimes produce ugly, muddy, or desaturated colors in the middle of the blend. My friends Wes and Anson pointed me towards Stuart Denman's post on using the CIE-LCh color-space for blending. It's quite detailed; I highly recommend you check it out.

Of course, I couldn't simply use Denman's JavaScript, because I'm a masochist and a pedant. No, in reality I just have different preferences regarding structuring my JavaScript, and I like the concept of a unified Color object, rather than standalone RGB, HSV, of CIE-LCh objects.

Short version of Denman's post: using the CIE-LCh color-space, we can create blends that smoothly transition perceptual brightness and saturation. However, because the conversion from RGB to CIE-LCh and back is somewhat expensive, it's not advisable to continually make those conversions during each step of an animation. Therefore, in my ColorTransition class, I create a number of steps using the CIE-LCh color-space to rough out the improved blend, then do simple RGB blends between those steps to save processing time.

I've included both full and minified versions of Color.js and ColorTransition.js, as well as a test setup for visualizing random blends.