Calculating a friendly font color based on the fill color – Google Apps Script

In Color Ramps for Google Apps Script I covered how to created heatmaps and other color ramps.

Picking a good contrast font color

One of the problems with a heatmap is that your font color may need to be changed so that it is visible against the chosen color. In fact there are W3 org guidelines for contrast. I apply that algorithm to decide whether to use black or white for the text color. I initially played around with contrasting using HSL and so on, but certain color combinations were just plain ugly, so in the end I settled for flipping between black and white. Here’s the whole section, where a ramp fill color is calculated, and then we use the calculated text color, based on the luminescence of the fill color.

// get the ramp color
var fillColor = new mcpher.colorProps(mcpher.rampLibraryRGB(rampList[l], mn, mx, v)) ;
// set the fill
cacheColor.setValue(fillColor.htmlHex,r,c);
// get a friendly font color for this fill
cacheFontColor.setValue(mcpher.rgbToHTMLHex(fillColor.textColor),r,c);

The supporting code for that is in a shared library, and reproduced below

Here’s a heatmap from a Google Spreadsheet, with the both the font colors and the fill calculated as above. For more information see Color Ramps for Google Apps Script

On the right, you’ll see some badges. For more information on how to add badges to your blog, and to see this embedded in Google Sites see Excel Liberation

Author: brucemcp

Leave a Reply

Your email address will not be published. Required fields are marked *