JavaScript color contraster

烂漫一生 提交于 2019-12-03 02:44:13

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.

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.

There is now a property called mix-blend-mode in CSS (currently just in draft) that can be used to achieve something similar to what you want.

.contrasting-text {
    mix-blend-mode: difference;
}

CodePen someone has put together demonstrating this: https://codepen.io/thebabydino/pen/JNWqLL

This is my fav resource to calculate the "readability" (contrast ratio) of two colors.

the W3C suggests a contrast ratio of at least 5:1 exists between text and background behind the text http://www.w3.org/TR/2007/WD-WCAG20-TECHS-20070517/Overview.html#G18

From the page:

The compliance rate shown above is the highest compliance rate met. The WCAG 2.0 level AA and proposed Section 508 refresh compliance level is based on achieving a contrast ratio of 3:1 for text with a size of 18 points (14 points if bolded) or larger or 4.5:1 for text with a size less than 18 points. The WCAG 2.0 level AAA compliance level is meet when a contrast ration of 7:1 is achieved for text less than 18 points and 4.5:1 for text 18 points (14 points if bolded) or larger.

Marco

In just one line this solves the problem:

function getContrast50($hexcolor)
{ 
  return (hexdec($hexcolor) > 0xffffff/2) ? 'white':'black'; 
}

If the contrast need to be reversed just swicth white with black and it does the trick. In php.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!