1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 | const d3 = require('d3');
|
14 | const d3cam02 = require('d3-cam02');
|
15 | const d3hsluv = require('d3-hsluv');
|
16 | const d3hsv = require('d3-hsv');
|
17 |
|
18 | const d3plus = {
|
19 | ...d3,
|
20 | ...d3cam02,
|
21 | ...d3hsluv,
|
22 | ...d3hsv
|
23 | };
|
24 |
|
25 | d3plus.interpolateJch = (start, end) => {
|
26 |
|
27 |
|
28 | const constant = x => () => x;
|
29 | const linear = (a, d) => t => a + t * d;
|
30 | const colorInterpolate = (a, b) => {
|
31 | const d = b - a;
|
32 | return d ? linear(a, d) : constant(isNaN(a) ? b : a);
|
33 | }
|
34 |
|
35 | start = d3.jch(start);
|
36 | end = d3.jch(end);
|
37 |
|
38 | const zero = Math.abs(start.h - end.h);
|
39 | const plus = Math.abs(start.h - (end.h + 360));
|
40 | const minus = Math.abs(start.h - (end.h - 360));
|
41 | if (plus < zero && plus < minus) {
|
42 | end.h += 360;
|
43 | }
|
44 | if (minus < zero && minus < plus) {
|
45 | end.h -= 360;
|
46 | }
|
47 |
|
48 | const startc = d3.hcl(start + '').c;
|
49 | const endc = d3.hcl(end + '').c;
|
50 | if (!startc) {
|
51 | start.h = end.h;
|
52 | }
|
53 | if (!endc) {
|
54 | end.h = start.h;
|
55 | }
|
56 |
|
57 | const J = colorInterpolate(start.J, end.J),
|
58 | C = colorInterpolate(start.C, end.C),
|
59 | h = colorInterpolate(start.h, end.h),
|
60 | opacity = colorInterpolate(start.opacity, end.opacity);
|
61 |
|
62 | return t => {
|
63 | start.J = J(t);
|
64 | start.C = C(t);
|
65 | start.h = h(t);
|
66 | start.opacity = opacity(t);
|
67 | return start + '';
|
68 | };
|
69 | };
|
70 |
|
71 | module.exports = d3plus;
|