Skip to content

Commit 4f58819

Browse files
committed
snippets: rgb to hsl color
1 parent 0ef3160 commit 4f58819

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

public/consolidated/javascript.json

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,17 @@
101101
],
102102
"contributors": [],
103103
"code": "function rgbToHex(r, g, b) {\n const toHex = (n) => {\n const hex = n.toString(16);\n return hex.length === 1 ? '0' + hex : hex;\n };\n \n return '#' + toHex(r) + toHex(g) + toHex(b);\n}\n\n// Usage:\nconsole.log(rgbToHex(255, 128, 0)); // Output: \"#ff8000\"\nconsole.log(rgbToHex(0, 255, 0)); // Output: \"#00ff00\"\n"
104+
},
105+
{
106+
"title": "RGB to HSL Color",
107+
"description": "Converts RGB color values to HSL color values.",
108+
"author": "pvictordev",
109+
"tags": [
110+
"color",
111+
"conversion"
112+
],
113+
"contributors": [],
114+
"code": "function rgbToHsl(r, g, b) {\n r /= 255;\n g /= 255;\n b /= 255;\n const max = Math.max(r, g, b),\n min = Math.min(r, g, b);\n let h, s, l;\n l = (max + min) / 2;\n\n if (max === min) {\n h = s = 0;\n } else {\n const d = max - min;\n s = l > 0.5 ? d / (2 - max - min) : d / (max + min);\n switch (max) {\n case r:\n h = (g - b) / d + (g < b ? 6 : 0);\n break;\n case g:\n h = (b - r) / d + 2;\n break;\n case b:\n h = (r - g) / d + 4;\n break;\n }\n h /= 6;\n }\n return { h: Math.round(h * 360), s: Math.round(s * 100), l: Math.round(l * 100) };\n}\n\n// Usage:\nconsole.log(rgbToHsl(255, 87, 51)); // { h: 14, s: 100, l: 60 }\nconsole.log(rgbToHsl(255, 255, 255)); // { h: 0, s: 0, l: 100 }\n"
104115
}
105116
]
106117
},
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
---
2+
title: RGB to HSL Color
3+
description: Converts RGB color values to HSL color values.
4+
author: pvictordev
5+
tags: color,conversion
6+
---
7+
8+
```js
9+
function rgbToHsl(r, g, b) {
10+
r /= 255;
11+
g /= 255;
12+
b /= 255;
13+
const max = Math.max(r, g, b),
14+
min = Math.min(r, g, b);
15+
let h, s, l;
16+
l = (max + min) / 2;
17+
18+
if (max === min) {
19+
h = s = 0;
20+
} else {
21+
const d = max - min;
22+
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
23+
switch (max) {
24+
case r:
25+
h = (g - b) / d + (g < b ? 6 : 0);
26+
break;
27+
case g:
28+
h = (b - r) / d + 2;
29+
break;
30+
case b:
31+
h = (r - g) / d + 4;
32+
break;
33+
}
34+
h /= 6;
35+
}
36+
return { h: Math.round(h * 360), s: Math.round(s * 100), l: Math.round(l * 100) };
37+
}
38+
39+
// Usage:
40+
console.log(rgbToHsl(255, 87, 51)); // { h: 14, s: 100, l: 60 }
41+
console.log(rgbToHsl(255, 255, 255)); // { h: 0, s: 0, l: 100 }
42+
```

0 commit comments

Comments
 (0)