Created
May 16, 2015 15:42
-
-
Save benjackwhite/83573ee5364df88163d9 to your computer and use it in GitHub Desktop.
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
/*! ColorGenerator v0.0.1 - MIT license */ | |
'use strict'; | |
/** | |
* Module dependencies | |
*/ | |
var hash = function(stringToHash) { | |
var value = 1; | |
for (var i = 0; i < stringToHash.length; i++) { | |
value = value * parseInt(stringToHash.charCodeAt(i)); | |
}; | |
if(value < Math.pow(16, 6)) | |
{ | |
value = Math.pow(value, 6); | |
} | |
return value.toString(16); | |
} | |
/** | |
* Module exports | |
*/ | |
module.exports = ColorGenerator; | |
/** | |
* @param str | |
* @return {} | |
* @api public | |
*/ | |
function ColorGenerator(sourceString) { | |
if (typeof sourceString !== 'string') throw (new Error('ColorGenerator was not passed a string')); | |
var hex = hash(sourceString).substr(0, 6); | |
var offset = 0.2; | |
var r = parseInt(hex.substr(0, 2), 16), | |
g = parseInt(hex.substr(2, 2), 16), | |
b = parseInt(hex.substr(4, 2), 16); | |
var lum = Math.sqrt(0.299 * r * r + 0.587 * g * g + 0.114 * b * b); | |
var isDark = (lum < 128); | |
if (!isDark) offset *= -1; | |
var oRGB = [ | |
Math.round(Math.min(Math.max(0, r + (r * offset)), 255)), | |
Math.round(Math.min(Math.max(0, g + (g * offset)), 255)), | |
Math.round(Math.min(Math.max(0, b + (b * offset)), 255)) | |
]; | |
var oHex = '', | |
c; | |
for (var i = 0; i < oRGB.length; i++) { | |
c = oRGB[i].toString(16); | |
oHex += ("00" + c).substr(c.length); | |
}; | |
return { | |
"hex": hex, | |
"rgb": [r, g, b], | |
"lum": lum, | |
"isDark": isDark, | |
"oRGB": oRGB, | |
"oHex": oHex | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment