Last active
June 7, 2017 23:16
-
-
Save webinista/00f114f8bd9d0ea53ed85cd058db8099 to your computer and use it in GitHub Desktop.
Convert from hsl to rgb string
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
const percentToFloat = (percentString) => { | |
return parseInt(percentString, 10) / 100; | |
} | |
/* | |
* Copied, pasted, and modified straight from the CSS4 spec | |
* https://drafts.csswg.org/css-color-4/#hsl-to-rgb | |
*/ | |
const hueToRgb = (t1, t2, hue) => { | |
let hueValue; | |
if(hue < 0) hue += 6; | |
if(hue >= 6) hue -= 6; | |
if(hue < 1) hueValue = (t2 - t1) * hue + t1; | |
else if(hue < 3) hueValue = t2; | |
else if(hue < 4) hueValue = (t2 - t1) * (4 - hue) + t1; | |
else hueValue = t1; | |
// Return a value between 0 and 255 | |
return hueValue * 255; | |
} | |
/* | |
* Based on math from | |
* http://www.niwa.nu/2013/05/math-behind-colorspace-conversions-rgb-hsl/ | |
* Does not yet handle space-separated hsl values. | |
*/ | |
export function hslToRgb(string) { | |
let rgb; | |
const color = string.replace('hsl(', '').replace(')', ''); | |
const [hue, sat, light] = color.split(','); | |
/* | |
* [0] Convert hue value to an angle. Not sure why we're dividing by 60. It works though! | |
* I think it's related to hueToRgb using +/-6 (6 * 60 = 360, or the degrees in an HSL wheel). | |
* | |
* [1, 2] Parse percentage values into floats so 40% becomes 0.4, etc | |
*/ | |
const [h, s, l] = [hue / 60, percentToFloat(sat), percentToFloat(light)]; | |
/* | |
* If there's no saturation, it's a gray. Need to multiply the lightness | |
* value by 255 and set r,g,b to that value. | |
*/ | |
if(s === 0) { | |
const gray = Math.round(l * 255); | |
rgb = [gray, gray, gray]; | |
} else { | |
// temp1 and temp2 don't really need names. they're just holders for these | |
// calculations | |
const temp1 = (l <= 0.5) ? l * (s + 1) : (l + s) - (l * s); | |
const temp2 = (l * 2) - temp1; | |
rgb = [ | |
hueToRgb(temp2, temp1, h + 2, true), | |
hueToRgb(temp2, temp1, h, true), | |
hueToRgb(temp2, temp1, h - 2, true) | |
]; | |
} | |
const rgbStr = `rgb(${rgb.join(', ')})`; | |
return rgbStr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment