Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save krabs-github/ec56e4f1c12cddf86ae9c551aa9d9e04 to your computer and use it in GitHub Desktop.
Save krabs-github/ec56e4f1c12cddf86ae9c551aa9d9e04 to your computer and use it in GitHub Desktop.
[JavaScript - Determine if Hex Color is Light or Dark] JavaScript - Determine if Hex Color is Light or Dark #JavaScript
function lightOrDark(color) {
// Check the format of the color, HEX or RGB?
if (color.match(/^rgb/)) {
// If HEX --> store the red, green, blue values in separate variables
color = color.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/);
r = color[1];
g = color[2];
b = color[3];
}
else {
// If RGB --> Convert it to HEX: http://gist.github.com/983661
color = +("0x" + color.slice(1).replace(
color.length < 5 && /./g, '$&$&'
)
);
r = color >> 16;
g = color >> 8 & 255;
b = color & 255;
}
// HSP equation from http://alienryderflex.com/hsp.html
hsp = Math.sqrt(
0.299 * (r * r) +
0.587 * (g * g) +
0.114 * (b * b)
);
// Using the HSP value, determine whether the color is light or dark
if (hsp>127.5) {
return 'light';
}
else {
return 'dark';
}
}
bgColor = "#EE7AB7"
brightness = lightOrDark(bgColor);
console.log(brightness, hsp)
@iaremarkus
Copy link

iaremarkus commented Apr 17, 2024

thanks this was useful to me! :)

PS: might need let r, g, b, hsp; at the top

@ThomasBurleson
Copy link

ThomasBurleson commented Dec 13, 2024

/**
 * Determine if a color is a light color
 * @see https://gist.github.com/krabs-github/ec56e4f1c12cddf86ae9c551aa9d9e04
 */
function isLightColor(color: string): boolean {
  let r, g, b;

  // Check the format of the color, HEX or RGB?
  if (color.match(/^rgb/)) {
    // If HEX --> store the red, green, blue values in separate variables
    const rgb = color.match(
      /^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/
    );

    r = rgb[1];
    g = rgb[2];
    b = rgb[3];
  } else {
    // If RGB --> Convert it to HEX: http://gist.github.com/983661
    const hexColor = +(
      '0x' + color.slice(1).replace(color.length < 5 && /./g, '$&$&')
    );

    r = hexColor >> 16;
    g = (hexColor >> 8) & 255;
    b = hexColor & 255;
  }

  // HSP equation from http://alienryderflex.com/hsp.html
  const hsp = Math.sqrt(0.299 * (r * r) + 0.587 * (g * g) + 0.114 * (b * b));

  // Using the HSP value, determine whether the color is light or dark
  // > 127.5 is 'light', <= 127.5 is 'dark'

  return hsp > 127.5;
}

@hrieke
Copy link

hrieke commented Sep 1, 2025

License for your code?

@krabs-github
Copy link
Author

krabs-github commented Sep 2, 2025

License for your code?

Whatever you want to do with it is fine. Consider it MIT licensed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment