gitscope
← marzneshin / v0.1.4 / app/dashboard/src/utils/color.ts
https://dev.kronoz.win/r/marzneshin.git
app/dashboard/src/utils/color.ts · TypeScript
Blame Raw
 1export function generateDistinctColors(numColors: number) {
 2  const hueStep = 360 / numColors;
 3  const saturation = 90;
 4  const lightness = 47;
 5  const colors = [];
 6
 7  for (let i = 0; i < numColors; i++) {
 8    const hue = ((i * hueStep) % 360) + 140;
 9    const color = hslToHex(hue, saturation, lightness);
10    colors.push(color);
11  }
12
13  return colors;
14}
15
16function hslToHex(h: number, s: number, l: number) {
17  h /= 360;
18  s /= 100;
19  l /= 100;
20
21  let r, g, b;
22
23  if (s === 0) {
24    r = g = b = l;
25  } else {
26    const hueToRgb = (p: number, q: number, t: number) => {
27      if (t < 0) t += 1;
28      if (t > 1) t -= 1;
29      if (t < 1 / 6) return p + (q - p) * 6 * t;
30      if (t < 1 / 2) return q;
31      if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
32      return p;
33    };
34
35    const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
36    const p = 2 * l - q;
37
38    r = Math.round(hueToRgb(p, q, h + 1 / 3) * 255);
39    g = Math.round(hueToRgb(p, q, h) * 255);
40    b = Math.round(hueToRgb(p, q, h - 1 / 3) * 255);
41  }
42
43  const toHex = (c: number) => {
44    const hex = c.toString(16);
45    return hex.length === 1 ? '0' + hex : hex;
46  };
47
48  return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
49}