Forked from krabs-github/JavaScript - Determine if Hex Color is Light or Dark.js
Created
December 16, 2024 14:46
-
-
Save CypherpunkSamurai/ca5f4b11eb64078d8ef01d1155a78781 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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment