Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

color.ts

61 lines1.5 KB

1export type HsvColor = {
2 h: number;
3 s: number;
4 v: number;
5};
6​
7export function hexToHsv(hex: string): HsvColor {
8 const numeric = Number.parseInt(hex.slice(1), 16);
9 const red = ((numeric >> 16) & 255) / 255;
10 const green = ((numeric >> 8) & 255) / 255;
11 const blue = (numeric & 255) / 255;
12 const max = Math.max(red, green, blue);
13 const min = Math.min(red, green, blue);
14 const delta = max - min;
15​
16 let hue = 0;
17 if (delta !== 0) {
18 if (max === red) {
19 hue = ((green - blue) / delta) % 6;
20 } else if (max === green) {
21 hue = (blue - red) / delta + 2;
22 } else {
23 hue = (red - green) / delta + 4;
24 }
25 hue *= 60;
26 if (hue < 0) hue += 360;
27 }
28​
29 return {
30 h: hue,
31 s: max === 0 ? 0 : delta / max,
32 v: max,
33 };
35​
36export function hsvToHex(hue: number, saturation: number, value: number) {
37 const normalizedHue = ((hue % 360) + 360) % 360;
38 const chroma = value * saturation;
39 const x = chroma * (1 - Math.abs(((normalizedHue / 60) % 2) - 1));
40 const match = value - chroma;
41 const [red, green, blue] =
42 normalizedHue < 60
43 ? [chroma, x, 0]
44 : normalizedHue < 120
45 ? [x, chroma, 0]
46 : normalizedHue < 180
47 ? [0, chroma, x]
48 : normalizedHue < 240
49 ? [0, x, chroma]
50 : normalizedHue < 300
51 ? [x, 0, chroma]
52 : [chroma, 0, x];
53​
54 return `#${[red, green, blue]
55 .map((channel) =>
56 Math.round((channel + match) * 255)
57 .toString(16)
58 .padStart(2, "0"),
59 )
60 .join("")}`;