Inverting A Color

Here's a one-liner in Javascript to invert a hex color.

Inverting A Color

Recently, I needed to display labels on arbitrarily colored backgrounds. I needed the labels to be visible so I decided to simply invert the background color and apply it to the label.

The input I was dealing with were colors expressed as a hex code. A hex code is a base-16 encoded numeric value that represents a color. #FFFFFF is white. #000000 is black. #FF0000 is true red. #ED0A3F is Crayola Crayon Red. #FF9900 is Amazon yellow. You get the picture.

Since each color is simply an integer value base-16 encoded, we can convert each of these values to it's base-10 counterpart. #FFFFFF becomes 16,777,215. #000000 becomes, well, 0. Amazon yellow (#FF9900) becomes 16,750,848.

These values range from 0 (white) to 16,777,215 (black). Since we have a highest value, the inverse of any color is just that color minus the highest value (in this case 16,777,215). So the inverse of black (#FFFFFF) is 16,777,215 - 16,777,215 which equals.... 0. Which is (#000000) white.

Amazon yellow (#FF9900) is 16,750,848.
16,777,215 - 16,750,848 = 26367
26367 converts back to #0066FF which is a very nice blue.

So that's it! I wrote this little one-liner in javascript for my purposes: