Choose white or black letters over color
Given a background color, what is the best way to determine if I should use black or white for the foreground color?
For example, could I use a formula based on the HSB values of the color?
It's for an app in which the background color is dynamic.
I have used a javscript based color picker on some of my sites, and the font color within the input box changes based on the values the picker chooses...
The code (Direct Code Link Here) for the script shows a specific location for the colorization of the input box the script is attached to.
Within that code you can see the formula:
0.213 * this.rgb[ 0 ] + 0.715 * this.rgb[ 1 ] + 0.072 * this.rgb[ 2 ]
With the result being:
< 0.5 ? '#FFF' : '#000';
or... (IF) less than 0.5 of the pure white (255) = 'White' (Otherwise) = 'Black';
You can extrapolate from that formula that:
0.213 * your RED value (0 - 255) +
0.715 * your Blue Value (0 - 255) +
0.072 * your Green value (0 - 255)
gives you a number
...and if that number is greater than .5,
you should opt for a Black font color, otherwise, go for white.
0.213 * 21 = 4.473
0.715 * 57 = 33.605
0.072 * 117 = 8.424
4.473 + 33.605 + 8.424 = 46.502
Since 46.502 is less than .5 of the pure white (255), we should use white on this background.
Hope this helps.