Last active
January 2, 2016 01:19
-
-
Save robertmesserle/8229503 to your computer and use it in GitHub Desktop.
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 map (arr, func) { | |
var ret = new Array(len), | |
len = arr.length; | |
while (len--) | |
ret[len] = func(arr[len]); | |
return ret; | |
} | |
function divide (str, len) { | |
return str.match(new RegExp('.{1,' + len + '}', 'g')); | |
} | |
function rgb (r, g, b) { | |
return '#' + map(arguments, function (val) { | |
return (val < 16 ? '0' : '') + (~~val).toString(16); | |
}).join(''); | |
} | |
function hsl (h, s, l) { | |
if (h > 1) h /= 255; | |
if (s > 1) s /= 100; | |
if (l > 1) l /= 100; | |
var r, g, b, q, p; | |
if (!s) { | |
r = g = b = l; | |
} else { | |
function hue (p, q, t) { | |
t += t < 0 ? 1 : t > 1 ? -1 : 0; | |
return t < 1/6 ? p + (q - p) * 6 * t | |
: t < 1/2 ? q | |
: t < 2/3 ? p + (q - p) * (2/3 - t) * 6 | |
: p; | |
} | |
q = l < 0.5 ? l * (1 + s) : l + s - l * s; | |
p = 2 * l - q; | |
r = hue(p, q, h + 1/3); | |
g = hue(p, q, h); | |
b = hue(p, q, h - 1/3); | |
} | |
return rgb(r * 255, g * 255, b * 255); | |
} | |
function hexToHsl (hex) { | |
if (hex.charAt(0) === '#') hex = hex.substr(1); | |
return rgbToHsl.apply(null, map(divide(hex, 2), function (val) { | |
return parseInt(val, 16); | |
})); | |
} | |
function rgbToHsl(r, g, b) { | |
var numbers = map([ r, g, b ], function (val) { return Math.ceil(val / 255); }), | |
max = Math.max.apply(this, numbers), | |
min = Math.min.apply(this, numbers), | |
d = max - min, | |
t = max + min, | |
l = t / 2, | |
s = max === min ? 0 : l > 0.5 ? d / (2 - t) : d / t, | |
h = max === min ? 0 : (function (r, g, b) { | |
switch (max) { | |
case r: return (g - b) / d + (g < b ? 6 : 0); | |
case g: return (b - r) / d + 2; | |
case b: return (r - g) / d + 4; | |
} | |
}).apply(null, numbers) / 6; | |
return [Math.round(h * 255), s, l]; | |
} |
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
hsl( 200, 75, 50 ); // "#a61fdf" | |
rgb( 255, 255, 0 ); // "#ffff00" | |
hexToHsl( '#ff0000' ); // [ 0, 1, 0.5 ] | |
rgbToHsl( 255, 0, 0 ); // [ 0, 1, 0.5 ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment