Debian Codegraph @

node/colorjs.io/src/spaces/lch.js

raw
1 import ColorSpace from "../ColorSpace.js";
2 import Lab from "./lab.js";
3 import { constrain as constrainAngle } from "../angles.js";
4 import { isNone } from "../util.js";
5
6 export default new ColorSpace({
7 id: "lch",
8 name: "LCH",
9 coords: {
10 l: {
11 refRange: [0, 100],
12 name: "Lightness",
13 },
14 c: {
15 refRange: [0, 150],
16 name: "Chroma",
17 },
18 h: {
19 refRange: [0, 360],
20 type: "angle",
21 name: "Hue",
22 },
23 },
24
25 base: Lab,
26 fromBase (Lab) {
27 // These methods are used for other polar forms as well, so we can't hardcode the ε
28 if (this.ε === undefined) {
29 // @ts-expect-error Property 'coords' does not exist on type 'string | ColorSpace'
30 let range = Object.values(this.base.coords)[1].refRange;
31 let extent = range[1] - range[0];
32 this.ε = extent / 100000;
33 }
34
35 // Convert to polar form
36 let [L, a, b] = Lab;
37 let isAchromatic = Math.abs(a) < this.ε && Math.abs(b) < this.ε;
38 let h = isAchromatic ? null : constrainAngle((Math.atan2(b, a) * 180) / Math.PI);
39 let C = isAchromatic ? 0 : Math.sqrt(a ** 2 + b ** 2);
40
41 return [L, C, h];
42 },
43 toBase (lch) {
44 // Convert from polar form
45 let [L, C, h] = lch;
46 let a = null,
47 b = null;
48
49 if (!isNone(h)) {
50 C = C < 0 ? 0 : C; // Clamp negative Chroma
51 a = C * Math.cos((h * Math.PI) / 180);
52 b = C * Math.sin((h * Math.PI) / 180);
53 }
54
55 return [L, a, b];
56 },
57
58 formats: {
59 lch: {
60 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <angle>"],
61 },
62 },
63 });