This example demonstrates how to remap a monochrome image using a custom color scale. You might use this technique as an alternative to a CSV- or JSON-based heatmap; binary images can store lots of data efficiently.
The source image is a global heightmap from the Shuttle Radar Topography Mission, released as part of NASA’s Blue Marble collection at 8km resolution. The topography data is stored in a simple black-and-white, 8-bit PNG. Darker values represent lower elevations, and lighter values represent higher elevations. Colors are read out of the image using the Canvas API.
Since there are eight bits per channel, elevation values range from 0 to 255. Since some land areas are below sea level, the source image uses a value of 14 to indicate sea level. The 5th, 50th and 95th percentiles for land elevation are 15, 35 and 132 respectively; quantiles are an effective way to maximize contrast while remapping colors, similar to auto-tone features popular in image editors.
The percentiles are used as the domain of a diverging linear scale; red values are below the median elevation, and blue values are above. Interpolating in HCL colorspace improves perception.
var color = d3.scale.linear()
.domain([15, 35, 132])
.range(["#d7191c", "#ffffbf", "#2c7bb6"])
.interpolate(d3.interpolateHcl);
Note that you could instead use a traditional rainbow color scale by interpolating hue from 0º to 360º. However, rainbow color scales are harmful, so please do your viewers a favor and use a perceptually-optimized scale instead.