DEV Community

Bluspace
Bluspace

Posted on

How to ensure contrast with the luminance formula

Why it matters

If you've ever built an application where a background color isn't always known when you're developing it- this includes social media apps, meme makers, color pickers, and more- you want to ensure users can see text regardless of the background color. But there is no single color for this: black on black is just as invisible as white on white.

The Luminance Formula

The luminance of a color simply represents its perceived brightness, which is more actually more complex than simply averaging the red, green, and blue components. Human eyes are more sensitive to green light than to red or blue light, so a weighted formula is used to calculate luminance.

Formula

If L represents luminance :
L= 0.299R + 0.587G + 0.114B
Where R is red, G is green, and B is blue.

Explanation

Red (0.299): The red component has the least impact on perceived brightness.
Green (0.587): Green is the most important component for perceived brightness.
Blue (0.114): Blue contributes the least to the overall brightness.

Human eyes are most sensitive to green light and least sensitive to blue, which is why green has the biggest weight in the formula.

Implementation

The actual code is simpler than the reasons behind it. Here's the function, implemented in JavaScript:

function getTextColor(hex) {
    hex = hex.replace(/^#/, '');

    let r = parseInt(hex.substring(0, 2), 16);
    let g = parseInt(hex.substring(2, 4), 16);
    let b = parseInt(hex.substring(4, 6), 16);

    let luminance = (0.299 * r + 0.587 * g + 0.114 * b);

    return luminance > 128 ? 'black' : 'white';
}
Enter fullscreen mode Exit fullscreen mode

Let's go through step by step:

  • We take in one parameter, the background color's hex value.
  • We split it into it's red, green, and blue color values.
  • We use the luminance function to find the luminance. If it's on the brighter side, we use black, otherwise, we return white.

Now you know how to use the luminance function! If you'd like useful and high-quality tools in your browser, visit https://tools.bluspace.net, made by the Bluspace team.

Top comments (0)