Debian Codegraph @

node/colorjs.io/src/deltaE/deltaEHCT.js

raw
1 import hct from "../spaces/hct.js";
2 import { viewingConditions } from "../spaces/hct.js";
3 import getColor from "../getColor.js";
4
5 /** @import { Coords } from "../types.js" */
6
7 const rad2deg = 180 / Math.PI;
8 const deg2rad = Math.PI / 180;
9 const ucsCoeff = [1.0, 0.007, 0.0228];
10
11 /**
12 * Convert HCT chroma and hue (CAM16 JMh colorfulness and hue) using UCS logic for a and b.
13 * @param {Coords} coords - HCT coordinates.
14 * @return {number[]}
15 */
16 function convertUcsAb (coords) {
17 // We want the distance between the actual color.
18 // If chroma is negative, it will throw off our calculations.
19 // Normally, converting back to the base and forward will correct it.
20 // If we have a negative chroma after this, then we have a color that
21 // cannot resolve to positive chroma.
22 if (coords[1] < 0) {
23 coords = hct.fromBase(hct.toBase(coords));
24 }
25
26 // Only in extreme cases (usually outside the visible spectrum)
27 // can the input value for log become negative.
28 // Avoid domain error by forcing a zero result via "max" if necessary.
29 const M =
30 Math.log(Math.max(1 + ucsCoeff[2] * coords[1] * viewingConditions.flRoot, 1.0)) /
31 ucsCoeff[2];
32 const hrad = coords[0] * deg2rad;
33 const a = M * Math.cos(hrad);
34 const b = M * Math.sin(hrad);
35
36 return [coords[2], a, b];
37 }
38
39 /**
40 * Color distance using HCT.
41 * @param {import("../types.js").ColorTypes} color
42 * @param {import("../types.js").ColorTypes} sample
43 * @returns {number}
44 */
45 export default function (color, sample) {
46 [color, sample] = getColor([color, sample]);
47
48 let [t1, a1, b1] = convertUcsAb(hct.from(color));
49 let [t2, a2, b2] = convertUcsAb(hct.from(sample));
50
51 // Use simple euclidean distance with a and b using UCS conversion
52 // and LCh lightness (HCT tone).
53 return Math.sqrt((t1 - t2) ** 2 + (a1 - a2) ** 2 + (b1 - b2) ** 2);
54 }