Skip to content

Instantly share code, notes, and snippets.

@lisaah
Last active December 24, 2015 19:27
Show Gist options
  • Save lisaah/c1abaa8b4fc99e96405f to your computer and use it in GitHub Desktop.
Save lisaah/c1abaa8b4fc99e96405f to your computer and use it in GitHub Desktop.
Change the brightness/darkness for a 3 or 6 digit hex color by adding white/black. Input '#' is optional, returns in 6-digit format like so '#ffffff'.
/**
* Takes a decimal value and changes it by the specified percentage (based off of the distance
* from 0 or 255, depending on whether the percentage change is negative or positive, respectively)
* @param {Number} value - number from [0, 255]
* @param {Number} percent - number from [0.0, 1.0]
* @return {Number} - number from [0, 255]
*/
function updateValue(value, percent) {
// Absolute distance from reference value
var distance = percent > 0 ? (255 - value) : value;
// Add the % change
return Math.round(value + (distance * percent));
}
/**
* Change the lumosity by adding the percentage of the distance to white/black.
* @param {String} color - color value with or without the '#', should be 3 or 6 digits
* @param {Number} percent - decimal percentage of the change, e.g. 0.10 indicates to
* lighten by 10%, -0.50 indicates to darken by 50%
* @return {String} - result hex 6-digit color, e.g. '#ffffff'
*/
function changeLumosity(color, percent) {
// Strip invalid characters
var hex = color.replace(/[^0-9a-f]/gi, '');
// 3-digit -> 6-digit
if (hex.length === 3) {
hex = hex.replace(/(.)/g, '$1$1');
}
// Hex -> decimal
var num = parseInt(hex, 16);
var r = updateValue(num >> 16, percent);
var g = updateValue((num >> 8) & 0x00FF, percent);
var b = updateValue(num & 0x0000FF, percent);
var hexOutput = (r << 16 | g << 8 | b).toString(16);
// Return formatted with '#' and padded with leading 0s
return '#' + ('000000' + hexOutput).slice(-6);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment