Last active
January 3, 2021 17:31
-
-
Save imohanvadivel/d8a149d4b102343f7d0a86041e997fa4 to your computer and use it in GitHub Desktop.
Simple logic to convert RGB color-space to HSL
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
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