Skip to content

Instantly share code, notes, and snippets.

@ConnectedReasoning
Forked from rafael25/brightnessByColor.js
Last active August 6, 2018 19:17
Show Gist options
  • Save ConnectedReasoning/54c3f0988d45a4f5bac8fca5db6fdafb to your computer and use it in GitHub Desktop.
Save ConnectedReasoning/54c3f0988d45a4f5bac8fca5db6fdafb to your computer and use it in GitHub Desktop.
Calculate brightness value by RGB or HEX color
brightnessByColor(color) {
let luminance = 0;
const isHEX = color.indexOf("#") == 0;
const isRGB = color.indexOf("rgb") == 0
let m, r, g, b;
if (isHEX) {
m = color.substr(1).match(color.length == 7 ? /(\S{2})/g : /(\S{1})/g);
if (m) {
r = parseInt(m[0], 16);
g = parseInt(m[1], 16);
b = parseInt(m[2], 16);
}
}
if (isRGB) {
m = color.match(/(\d+){3}/g);
if (m) {
r = m[0];
g = m[1];
b = m[2];
}
}
if (typeof r != "undefined") {
luminance = ((r*299)+(g*587)+(b*114))/1000;
}
return luminance;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment