DEV Community

Discussion on: Write a function that outputs a pleasant text color hex given a background color hex

Collapse
 
nektro profile image
Meghan (she/her) • Edited
// assumes bgColor is a rgb() string: "rgb(66, 134, 244)"
function getTextColor(c) {
  let rgb = c.substring(4, bgColor.indexOf(')')).split(", ").map(x => parseInt(x));
  let o = Math.round(((parseInt(rgb[0]) * 299) + (parseInt(rgb[1]) * 587) + (parseInt(rgb[2]) * 114)) /1000);
  return ((o > 125) ? ('black') : ('white'));
}
Collapse
 
ben profile image
Ben Halpern

So this returns black or white, but what if the ideal solution returned, perhaps a very dark version of the background color. Like, dark blue on light blue might be more pleasant than black on light blue etc.

Collapse
 
nektro profile image
Meghan (she/her)

Would this work then? get color, convert color to HSL, return L - 100 % 100