Created
May 22, 2015 11:15
-
-
Save romeshniriella/e613ca357be861101a84 to your computer and use it in GitHub Desktop.
Random Background & eye-friendly Fore-color generation
This file contains hidden or 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
function shadeColor2(color, percent, hash) { | |
var f=parseInt((hash? color.slice(1) : color),16), | |
t=percent<0?0:255, | |
p=percent<0?percent*-1:percent, | |
R=f>>16, | |
G=f>>8&0x00FF, | |
B=f&0x0000FF; | |
return (0x1000000 | |
+(Math.round((t-R)*p)+R)*0x10000 | |
+(Math.round((t-G)*p)+G)*0x100 | |
+(Math.round((t-B)*p)+B)) | |
.toString(16) | |
.slice(1); | |
} | |
function getRandomColor(hash) { | |
var letters = '0123456789ABCDEF'.split(''); | |
var color = ''; | |
for (var i = 0; i < 6; i++) { | |
color += letters[Math.floor(Math.random() * 16)]; | |
} | |
var l = getLuminance(color); | |
if(l > 90){ | |
//console.log("shading: " + color); | |
color = shadeColor2(color, -0.25); | |
} | |
return (hash ? '#' : '') + color; | |
} | |
function invertColor(hexTripletColor, hash) { | |
var color = hexTripletColor, rgb; | |
if (hash) { | |
color = color.substring(1); // remove # | |
} | |
color = rgb = parseInt(color, 16); // convert to integer | |
color = 0xFFFFFF ^ color; // invert three bytes | |
//console.log("BG: " + getLuminance(rgb)); | |
//console.log("TXT: " + getLuminance(color)); | |
var lr = getLuminance(rgb); | |
var lt = getLuminance(color); | |
var ma = (lr - lt); | |
console.log("ma: " + ma); | |
if(ma < -20){ | |
//console.log("shading txt: " + color); | |
color = shadeColor2(color, -1); | |
}else if(ma < -60){ | |
//console.log("shading txt: " + color); | |
color = shadeColor2(color, -0.5); | |
}else if(ma > 7){ | |
//console.log("shading txt: " + color); | |
color = shadeColor2(color, 1); | |
} | |
color = color.toString(16); // convert to hex | |
color = ("000000" + color).slice(-6); // pad with leading zeros | |
color = (hash ? "#" : '') + color; // prepend # | |
return color; | |
} | |
function getLuminance(rgb){ | |
rgb = parseInt(rgb, 16); | |
// check for brightness or original color | |
var r = (rgb >> 16) & 0xff; // extract red | |
var g = (rgb >> 8) & 0xff; // extract green | |
var b = (rgb >> 0) & 0xff; // extract blue | |
var luma = 0.2126 * r + 0.7152 * g + 0.0722 * b; // per ITU-R BT.709 | |
return luma; | |
} | |
// usage | |
var bg = getRandomColor(true); // true implies we need the # in returned color code | |
$("#bg .lbl").text(bg); | |
$("#bg").css('background-color', bg); | |
var ibg = invertColor(bg, true); // true implies we need the # in returned color code | |
$("#text").css('color', ibg); | |
$("#text .lbl").text(ibg); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment