Skip to content

Instantly share code, notes, and snippets.

@imohanvadivel
Last active Jan 3, 2021
Embed
What would you like to do?
Simple logic to convert RGB color-space to HSL
class color {
static getLightness(R, G, B) {
const r = R / 255,
g = G / 255,
b = B / 255;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
return (max + min) / 2;
}
static getSaturation(R, G, B, l) {
if (R === G && G === B) return 0;
const r = R / 255,
g = G / 255,
b = B / 255;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
if (l <= 0.5) return (max - min) / (max + min);
else if (l > 0.5) return (max - min) / (2 - max - min);
}
static getHue(R, G, B) {
if (R === G && G === B) return 0;
const r = R / 255,
g = G / 255,
b = B / 255;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
let hue;
if (max === r) hue = (g - b) / (max - min);
else if (max === g) hue = 2 + (b - r) / (max - min);
else if (max === b) hue = 4 + (r - g) / (max - min);
return hue * 60;
}
static hexTohsl(str) {
let rgb = hexToDecimal(str);
let l = color.getLightness(...rgb);
let s = color.getSaturation(...rgb, l);
let h = color.getHue(...rgb);
if (h < 0) h += 360;
return {
h,
s: (s * 100),
l: (l * 100),
};
}
static rgbTohsl(...rgb) {
let l = color.getLightness(...rgb);
let s = color.getSaturation(...rgb, l);
let h = color.getHue(...rgb);
if (h < 0) h += 360;
return { h, s: s*100, l: l*100 };
}
}
function getHexArray(str) {
let hex = str.trim().toLowerCase().replace(/^#/, "");
hex = hex.length === 3 ? `${hex}${hex}` : hex;
const result = hex.match(/(\d|[a-f]){2}/g);
if (!result || result.length !== 3) throw new Error("Invalid Hex String");
return result;
}
function hexToDecimal(ary) {
let hex = ary;
if (!Array.isArray(ary)) hex = getHexArray(hex);
return hex.map((c) => parseInt(c, 16));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment