-
Notifications
You must be signed in to change notification settings - Fork 2
/
hsv.js
95 lines (88 loc) · 1.89 KB
/
hsv.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import { setAlpha } from "./utils.js";
/**
* @typedef {number[]} hsv hue, saturation, value.
*
* All components in the range 0 <= x <= 1
* @see {@link https://en.wikipedia.org/wiki/HSL_and_HSV}
*/
/**
* Updates a color based on HSV values and alpha.
* @alias module:pex-color.fromHSV
* @param {import("./color.js").color} color
* @param {number} h
* @param {number} s
* @param {number} v
* @param {number} [a]
* @returns {import("./color.js").color}
*/
export function fromHSV(color, h, s, v, a) {
const i = Math.floor(h * 6);
const f = h * 6 - i;
const p = v * (1 - s);
const q = v * (1 - f * s);
const t = v * (1 - (1 - f) * s);
switch (i % 6) {
case 0:
color[0] = v;
color[1] = t;
color[2] = p;
break;
case 1:
color[0] = q;
color[1] = v;
color[2] = p;
break;
case 2:
color[0] = p;
color[1] = v;
color[2] = t;
break;
case 3:
color[0] = p;
color[1] = q;
color[2] = v;
break;
case 4:
color[0] = t;
color[1] = p;
color[2] = v;
break;
case 5:
color[0] = v;
color[1] = p;
color[2] = q;
break;
}
return setAlpha(color, a);
}
/**
* Returns a HSV representation of a given color.
* @alias module:pex-color.toHSV
* @param {import("./color.js").color} color
* @param {Array} out
* @returns {hsv}
*/
export function toHSV([r, g, b, a], out = []) {
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
out[2] = max;
const d = max - min;
out[1] = max === 0 ? 0 : d / max;
if (max === min) {
out[0] = 0; // achromatic
} else {
switch (max) {
case r:
out[0] = (g - b) / d + (g < b ? 6 : 0);
break;
case g:
out[0] = (b - r) / d + 2;
break;
case b:
out[0] = (r - g) / d + 4;
break;
}
out[0] /= 6;
}
return setAlpha(out, a);
}