Skip to content

Instantly share code, notes, and snippets.

@slamkajs
Created January 4, 2017 19:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slamkajs/91cdd6c3f66b0eccbc6a3e56beb3334d to your computer and use it in GitHub Desktop.
Save slamkajs/91cdd6c3f66b0eccbc6a3e56beb3334d to your computer and use it in GitHub Desktop.
String function that converts a hex value (e.g., #FFFFFF) into a percentage between 0 and 1. The darker the color, the closer the value will be to zero. The lighter the color, the closer the value will be to one.
/**
* HEX TO COLOR TONE
* Convert a hex string for colors into a percentage of color tone
* This function takes accessibility into account when color correcting the brightness differences between RGB
*
* @return float(0, 1)
* black = 0
* white = 1
**/
String.prototype.getColorBrightness = function() {
var c,
blueMultiplier = .068,
blueVal,
greenMultiplier = .691,
greenVal,
redMultiplier = .241,
redVal,
currColorTone,
maxColorTone = 255; // 255 is the maximum hue value you can use
// MAKE SURE THE CURRENT STRING IS A HEX STRING
if(/^#([A-Fa-f0-9]{3}){1,2}$/.test(this)) {
// CONVERT INTO ARRAY
c= this.substring(1).split('');
if(c.length== 3){
c= [c[0], c[0], c[1], c[1], c[2], c[2]];
}
c= '0x'+c.join('');
// CONVERT HEX TO FLOAT FOR EACH COLOR
redVal = Math.pow((c>>16)&255, 2); // value to the power of 2
greenVal = Math.pow((c>>8)&255, 2); // value to the power of 2
blueVal = Math.pow(c&255, 2); // value to the power of 2
// CALCULATE CURRENT COLOR TONE FROM COLORS
currColorTone = Math.sqrt((redVal * redMultiplier) + (greenVal * greenMultiplier) + (blueVal * blueMultiplier));
/**
* GET COLOR TONE PERCENTAGE
**/
return currColorTone / maxColorTone;
}
throw new Error('Bad Hex');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment