Last active
August 29, 2015 14:22
-
-
Save serkanberksoy/d90968c8a4fd7806c316 to your computer and use it in GitHub Desktop.
Color Luminance
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
/* | |
This is the solution that I use in my projects for dynamic colors. | |
Don't know where I got it. | |
ColorLuminance("#69c", 0); // returns "#6699cc" | |
ColorLuminance("6699CC", 0.2); // "#7ab8f5" - 20% lighter | |
ColorLuminance("69C", -0.5); // "#334d66" - 50% darker | |
ColorLuminance("000", 1); // "#000000" - true black cannot be made lighter! | |
Real life example: | |
function getCityColor(mainColor, maxVote, votePercentage) | |
{ | |
var result = "#E8DFD9"; // default | |
var lightningStep = 0.1; | |
var currentLightning = 0; | |
var step = 5; | |
for(var i = parseInt(maxVote); i > 0; i = i - step) | |
{ | |
if(votePercentage > i) | |
{ | |
result = ColorLuminance(mainColor, currentLightning); | |
break; | |
} | |
else | |
{ | |
currentLightning += lightningStep; | |
} | |
} | |
return result; | |
} | |
*/ | |
function ColorLuminance(hex, lum) { | |
// validate hex string | |
hex = String(hex).replace(/[^0-9a-f]/gi, ''); | |
if (hex.length < 6) { | |
hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2]; | |
} | |
lum = lum || 0; | |
// convert to decimal and change luminosity | |
var rgb = "#", c, i; | |
for (i = 0; i < 3; i++) { | |
c = parseInt(hex.substr(i*2,2), 16); | |
c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16); | |
rgb += ("00"+c).substr(c.length); | |
} | |
return rgb; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment