Skip to content

Commit b0929c8

Browse files
committed
feat: add RGB to HSL color format conversion algorithm
1 parent 3423829 commit b0929c8

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed

Conversions/RgbHslConversion.js

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
/**
2+
* Given a color in RGB format, convert it to HSL format.
3+
*
4+
* For more info: https://www.niwa.nu/2013/05/math-behind-colorspace-conversions-rgb-hsl/
5+
*
6+
* @param {number[]} colorRgb - One dimensional array of integers (RGB color format).
7+
* @returns {number[]} - One dimensional array of integers (HSL color format).
8+
*
9+
* @example
10+
* const colorRgb = [24, 98, 118]
11+
*
12+
* const result = rgbToHsl(colorRgb)
13+
*
14+
* // The function returns the corresponding color in HSL format:
15+
* // result = [193, 66, 28]
16+
*/
17+
18+
const checkRgbFormat = (colorRgb) => {
19+
if (colorRgb[0] <= 255 && colorRgb[0] >= 0) {
20+
if (colorRgb[1] <= 255 && colorRgb[1] >= 0) {
21+
if (colorRgb[2] <= 255 && colorRgb[2] >= 0) {
22+
return true
23+
}
24+
}
25+
}
26+
return false
27+
}
28+
29+
const rgbToHsl = (colorRgb) => {
30+
if (checkRgbFormat(colorRgb) === false) {
31+
return 'Input is not a valid RGB color.'
32+
}
33+
34+
let colorHsl = colorRgb
35+
36+
let red = Math.round(colorRgb[0])
37+
let green = Math.round(colorRgb[1])
38+
let blue = Math.round(colorRgb[2])
39+
40+
const limit = 255
41+
42+
colorHsl[0] = red / limit
43+
colorHsl[1] = green / limit
44+
colorHsl[2] = blue / limit
45+
46+
let minValue = Math.min(...colorHsl)
47+
let maxValue = Math.max(...colorHsl)
48+
49+
let channel = 0
50+
51+
if (maxValue === colorHsl[1]) {
52+
channel = 1
53+
} else if (maxValue === colorHsl[2]) {
54+
channel = 2
55+
}
56+
57+
let luminance = (minValue + maxValue) / 2
58+
59+
let saturation = 0
60+
61+
if (minValue !== maxValue) {
62+
if (luminance <= 0.5) {
63+
saturation = (maxValue - minValue) / (maxValue + minValue)
64+
} else {
65+
saturation = (maxValue - minValue) / (2 - maxValue - minValue)
66+
}
67+
}
68+
69+
let hue = 0
70+
71+
if (saturation !== 0) {
72+
if (channel === 0) {
73+
hue = (colorHsl[1] - colorHsl[2]) / (maxValue - minValue)
74+
} else if (channel === 1) {
75+
hue = 2 + (colorHsl[2] - colorHsl[0]) / (maxValue - minValue)
76+
} else {
77+
hue = 4 + (colorHsl[0] - colorHsl[1]) / (maxValue - minValue)
78+
}
79+
}
80+
81+
hue *= 60
82+
83+
if (hue < 0) {
84+
hue += 360
85+
}
86+
87+
colorHsl[0] = Math.round(hue)
88+
colorHsl[1] = Math.round(saturation * 100)
89+
colorHsl[2] = Math.round(luminance * 100)
90+
91+
return colorHsl
92+
}
93+
94+
export { rgbToHsl }

0 commit comments

Comments
 (0)