Skip to content

Instantly share code, notes, and snippets.

@Kamilczak020
Last active November 23, 2017 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kamilczak020/47e51ab27810529b343111df435a01fb to your computer and use it in GitHub Desktop.
Save Kamilczak020/47e51ab27810529b343111df435a01fb to your computer and use it in GitHub Desktop.
Hex to HSL and HSL to Hex
/**
* Representation of color in HSL (hue, saturation, luminance) format.
*/
interface HslColor {
hue: number;
saturation: number;
luminance: number;
}
/**
* Converts hex color string to hsl object
* @param color color string in hex representation
*/
function hexToHsl(color: string): HslColor {
const red = parseInt(color.substr(1, 2), 16) / 255;
const green = parseInt(color.substr(3, 2), 16) / 255;
const blue = parseInt(color.substr(5, 2), 16) / 255;
const max = Math.max(red, green, blue);
const min = Math.min(red, green, blue);
const delta = max - min;
let hue;
if (delta === 0) {
hue = 0;
}
else if (max === red) {
hue = 60 * (((green - blue) / delta) % 6);
}
else if (max === green) {
hue = 60 * (((green - blue) / delta) + 2);
}
else if (max === blue) {
hue = 60 * (((green - blue) / delta) + 4);
}
const luminance = (max + min) / 2;
const saturation = delta === 0 ? 0 : delta / (1 - Math.abs(2 * luminance - 1));
return {hue, saturation, luminance};
}
/**
* Convert HSL color object to hex string
* @param color color object in HSL representation
*/
function hslToHex(color: HslColor) {
const c = (1 - Math.abs(2 * color.luminance - 1)) * color.saturation;
const x = c * (1 - Math.abs((color.hue / 60) % 2 - 1));
const m = color.luminance - c / 2;
let rgbValue: {r: number, g: number, b: number};
if (color.hue >= 0 && color.hue < 60) {
rgbValue = {r: c, g: x, b: 0};
}
else if (color.hue >= 60 && color.hue < 120) {
rgbValue = {r: x, g: c, b: 0};
}
else if (color.hue >= 120 && color.hue < 180) {
rgbValue = {r: 0, g: c, b: x};
}
else if (color.hue >= 180 && color.hue < 240) {
rgbValue = {r: 0, g: x, b: c};
}
else if (color.hue >= 240 && color.hue < 300) {
rgbValue = {r: x, g: 0, b: c};
}
else if (color.hue >= 300 && color.hue < 360) {
rgbValue = {r: c, g: 0, b: x};
}
const red = Math.round((rgbValue.r + m) * 255);
const green = Math.round((rgbValue.g + m) * 255);
const blue = Math.round((rgbValue.b + m) * 255);
return '#' + red.toString(16) + green.toString(16) + blue.toString(16);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment