Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript color contraster

I'm looking for a technique where we could programmatically pick the best color contrast to apply on text over HTML elements of different (unpredictable) background colors.

Since the HTML elements will have different colors, we're looking for a technique that will be able to determine what is the color of the content behind the text, and then adapt the text's color to use the one with the best contrast.

I'm quite sure this can't be CSS only, I've looked for Jquery solutions but couldn't find any... anyone has a clue?

[UPDATE] : Based on the first replies, I guess I need to rephrase. Imagine that I'm building a image sharing service and I want to allow people to tag on the pictures themselves. The pictures can be of any color. How can I pick up the right color of the tags, for each different picture?

like image 619
Julien Genestoux Avatar asked Apr 13 '11 14:04

Julien Genestoux


2 Answers

I think this might save any future researchers a little time, this works perfectly for me. Plug in the red green and blue values into the function and it outputs "dark-text" or "light-text".

var darkOrLight = function(red, green, blue) {
  var brightness;
  brightness = (red * 299) + (green * 587) + (blue * 114);
  brightness = brightness / 255000;

  // values range from 0 to 1
  // anything greater than 0.5 should be bright enough for dark text
  if (brightness >= 0.5) {
    return "dark-text";
  } else {
    return "light-text";
  }
}

Using some code from http://particletree.com/notebook/calculating-color-contrast-for-legible-text/ from @David's answer.

like image 81
Alex Marchant Avatar answered Sep 24 '22 04:09

Alex Marchant


Take a look at http://www.0to255.com . Just a moment's glance at the gradients the site presents will light you right up. You'll have to puzzle, but only for about 20 seconds. It's a great site for such problems and a terrific source of ideas for programmatic solutions. And there's no math involved: just plug in some bytes for rgb vals and go.

like image 2
Pete Wilson Avatar answered Sep 21 '22 04:09

Pete Wilson