UNPKG

2.03 kBJavaScriptView Raw
1/*
2Copyright 2019 Adobe. All rights reserved.
3This file is licensed to you under the Apache License, Version 2.0 (the "License");
4you may not use this file except in compliance with the License. You may obtain a copy
5of the License at http://www.apache.org/licenses/LICENSE-2.0
6
7Unless required by applicable law or agreed to in writing, software distributed under
8the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9OF ANY KIND, either express or implied. See the License for the specific language
10governing permissions and limitations under the License.
11*/
12
13const d3 = require('d3');
14const d3cam02 = require('d3-cam02');
15const d3hsluv = require('d3-hsluv');
16const d3hsv = require('d3-hsv');
17
18const d3plus = {
19 ...d3,
20 ...d3cam02,
21 ...d3hsluv,
22 ...d3hsv
23};
24
25d3plus.interpolateJch = (start, end) => {
26 // constant, linear, and colorInterpolate are taken from d3-interpolate
27 // the colorInterpolate function is `nogamma` in the d3-interpolate's color.js
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
71module.exports = d3plus;