Skip to content

Instantly share code, notes, and snippets.

@hettiger
Created November 8, 2018 23:08
Show Gist options
  • Save hettiger/455beeaf7c08d277527849f831363684 to your computer and use it in GitHub Desktop.
Save hettiger/455beeaf7c08d277527849f831363684 to your computer and use it in GitHub Desktop.
RGB to HSL
/**
* @see https://de.wikipedia.org/wiki/HSV-Farbraum#Umrechnung_RGB_in_HSV/HSL
*/
private convertRgbToHsl(rgbColor: { r: number; g: number; b: number; }): { h: number; s: number; l: number; } {
let h: number;
let s: number;
let l: number;
let { r, g, b } = rgbColor;
[ r, g, b ] = [ r, g, b ].map((value) => value / 255);
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
if (max === min) {
h = 0;
} else if (max === r) {
h = 60 * ((g - b) / (max - min));
} else if (max === g) {
h = 60 * (2 + (b - r) / (max - min));
} else if (max === b) {
h = 60 * (4 + (r - g) / (max - min));
}
if (h < 0) {
h += 360;
}
if (max === 0 || min === 1) {
s = 0;
} else {
s = ((max - min) / (1 - Math.abs(max + min - 1))) * 100;
}
l = (max + min) / 2 * 100;
[ h, s, l ] = [ h, s, l ].map((value) => Math.round(value));
return { h, s, l };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment