October 30th, 2007

Client-side color updates for dynamic graphics

If you're generating images dynamically, it's sometimes feasible to update the colors immediately and cheaply on the client side.

AutoMotivator is a motivational poster generator that offers a quick preview of what a poster will look like. Here's an example poster:

There are several distinct elements. The title is the red text "HOPE".

For the interactive preview, the border and title color, title string, and lower white text string can be updated independently.

My initial design used a transparent colored PNG for the title in the preview:

Each time the color was updated, I sent an Ajax request to the server for a new colored title, waited for the response, then replaced the old title with the new one when it arrived. It was pretty fast, but there's an even faster, easier way.

Instead of defining the interior of the title with a colored PNG, it's possible to define the exterior of the title with a black PNG that acts as a stencil.

All that remains is to wrap the stencil in a div with a background color style. The stencil only changes when the string is changed; color updates to the wrapping div can be made instantly with JavaScript.

background: #DD0000

background: blue

background: green

This won't work in all situations, but when it can work for you, it's a great way to get fast updates with dynamic content.