Skip to content

Instantly share code, notes, and snippets.

@BigRaj
Last active January 24, 2024 22:39
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 BigRaj/68388188743a62adbe087cc2dfb0ef4c to your computer and use it in GitHub Desktop.
Save BigRaj/68388188743a62adbe087cc2dfb0ef4c to your computer and use it in GitHub Desktop.
const ColorBrightness = (color, percent) => {
//default percent to itself or the new percentage
percent = percent || 0;
// guard clause for out of range
if(percent > 100 || percent < -100) return;
// converting whole numbers down to percentages.
if(percent > 1 || percent < -1){
console.log('assuming percentages as whole number between -100 and 100');
percent = percent/100;
}
// Break the hex apart into individual colors
var num = parseInt(color.replace("#",""), 16),
R = (num >> 16),
G = (num >> 8 & 0x00FF),
B = (num & 0x0000FF);
//if percent is over 0, lighten based on the distance between current color and #ffffff
if(percent > 0){
R = Math.round(R + (((255 - R) * percent)));
G = Math.round(G + (((255 - G) * percent)));
B = Math.round(B + (((255 - B) * percent)));
console.log(R,G,B);
}
// if percent is under 0, darken based on the distance between current color and #000000
if(percent < 0){
R = Math.round(R - ((R * Math.abs(percent))));
G = Math.round(G - ((G * Math.abs(percent))));
B = Math.round(B - ((B * Math.abs(percent))));
console.log(R,G,B);
}
// IF 0 RETURNS CURRENT HEX
// Returns a hex value
return "#" + (0x1000000 + (R)*0x10000 + (G)*0x100 + (B)).toString(16).slice(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment