Last active
July 8, 2020 22:07
-
-
Save akpersad/e8246e70210d0fbc8abc35dbb4a47fdc to your computer and use it in GitHub Desktop.
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 numChecker = (num, min, max) => (num < min ? min : num > max ? max : num); | |
const rgb2hsv = (r, g, b) => { | |
let rabs, gabs, babs, rr, gg, bb, h, s, v, diff, diffc, percentRoundFn; | |
rabs = r / 255; | |
gabs = g / 255; | |
babs = b / 255; | |
(v = Math.max(rabs, gabs, babs)), (diff = v - Math.min(rabs, gabs, babs)); | |
diffc = (c) => (v - c) / 6 / diff + 1 / 2; | |
percentRoundFn = (num) => Math.round(num * 100) / 100; | |
if (diff == 0) { | |
h = s = 0; | |
} else { | |
s = diff / v; | |
rr = diffc(rabs); | |
gg = diffc(gabs); | |
bb = diffc(babs); | |
if (rabs === v) { | |
h = bb - gg; | |
} else if (gabs === v) { | |
h = 1 / 3 + rr - bb; | |
} else if (babs === v) { | |
h = 2 / 3 + gg - rr; | |
} | |
if (h < 0) { | |
h += 1; | |
} else if (h > 1) { | |
h -= 1; | |
} | |
} | |
return { | |
h: Math.round(h * 360), | |
s: percentRoundFn(s * 100), | |
v: percentRoundFn(v * 100), | |
}; | |
}; | |
const tempToHSL = (tmpKelvin) => { | |
tmpKelvin = numChecker(tmpKelvin, 1000, 40000) / 100; | |
const hash = { | |
r: | |
tmpKelvin <= 66 | |
? 255 | |
: Math.round( | |
numChecker( | |
329.698727446 * | |
Math.pow(tmpKelvin - 60, -0.1332047592), | |
0, | |
255 | |
) | |
), | |
g: | |
tmpKelvin <= 66 | |
? Math.round( | |
numChecker( | |
99.4708025861 * Math.log(tmpKelvin) - 161.1195681661, | |
0, | |
255 | |
) | |
) | |
: Math.round( | |
numChecker( | |
288.1221695283 * | |
Math.pow(tmpKelvin - 60, -0.0755148492), | |
0, | |
255 | |
) | |
), | |
b: | |
tmpKelvin >= 66 | |
? 255 | |
: tmpKelvin <= 19 | |
? 0 | |
: Math.round( | |
numChecker( | |
138.5177312231 * Math.log(tmpKelvin - 10) - | |
305.0447927307, | |
0, | |
255 | |
) | |
), | |
}; | |
return rgb2hsv(hash.r, hash.g, hash.b); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment