Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for color stops in interpolate() [WIP] #77

Merged
merged 7 commits into from
May 15, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added .github/evenly-spaced-vs-positions.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
38 changes: 35 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,25 @@ let custom_interpolator = culori.interpolate(['blue', 'red'], 'lch', {

There are a few interpolation methods available, listed below. Depending on the channel, the numeric values can be interpreted/interpolated in various _modes_. The hue channel, for example, is interpolated by taking into account the _shortest path around the hue circle_ (`interpolateHue`). And the `interpolateAlpha` mode assumes an _undefined_ alpha is `1`.

#### Color stop positions

You can specify positions of color stops to interpolate in the way they're defined in the [CSS Images Module Level 4][css-images-4] specification:

```js
culori.interpolate(['red', ['green', 0.25], 'blue']);
```

In the image below, you can see the effect of interpolating with evenly-spaced colors (1) vs. positioned colors stops (2):

<img src='./.github/evenly-spaced-vs-positions.png' width='263'/>

To specify a positioned color stop, use an array that contains the color followed by its position. For omitted (implicit) positions, we apply the rules [from the spec][css-images-4]:

1. if the first color doesn't have a position, it's assumed to be `0`; if the last color doesn't have a position, it's assumed to be `1`;
2. any other color stops that don't have a position will be evenly distributed along the gradient line.

Color stop positions should be in increasing order.

#### Interpolation methods

You'll use these methods when you want to override how colors get interpolated in a specific color space, or when defining the default interpolation for custom color spaces.
Expand Down Expand Up @@ -466,7 +485,11 @@ culori.random();
// => { mode: 'rgb', r: 0.75, g: 0.12, b: 0.99 }
```

You can specify constraints for each individual channel in the color space, as either a _fixed number_ or an _interval_:
#### Specifying constraints

Random colors are, by definition, all over the color space and not all of them will look particularly nice. Some color spaces, such as HSL or HSV, are also biased towards colors close to black and/or white, because of the way these color spaces stretch the RGB cube into cyllinders.

For more control on how the colors are generated, you can specify constraints for each individual channel in the color space. Constraints can be either a _constant number_ or an _interval_ from where to pick the channel value:

```js
culori.random('hsv', {
Expand All @@ -475,9 +498,17 @@ culori.random('hsv', {
});
```

The resulting color will not include an _alpha_ value, unless you include it in the list of constraints.
The _alpha_ channel is excluded by default. To obtain colors with random alpha values, include a constraint for `alpha`:

```js
culori.random('lrgb', { alpha: [0, 1] });
```

#### Displayable random colors

The value for any channel in the color space for which there are no constraints will be picked from the entire range of that channel. However, some color spaces, such as LAB or LCH, don't have explicit ranges for certain channels; for these, some approximate ranges [have been pre-computed](https://github.com/evercoder/culori/blob/master/tools/ranges.js) as the limits of the displayable sRGB gamut.

The value for any channel in the color space for which there are no constraints will be picked from the entire range of that channel. However, some color spaces, such as LAB or LCH, don't have explicit ranges for certain channels; for these, some approximate ranges [have been pre-computed](https://github.com/evercoder/culori/blob/master/tools/ranges.js) as the limits of the displayable sRGB gamut. Even with these ranges in place, a combination of channel values may not be displayable. You can use [`culori.displayable()`](#culoriDisplayable) to check this, and [`culori.clamp()`](#culoriClamp) to obtain a displayable version.
Even with these ranges in place, a combination of channel values may not be displayable. Check if that's the case with [`culori.displayable()`](#culoriDisplayable), and pass the color through [`culori.clamp()`](#culoriClamp) to obtain a displayable version.

### Extending culori

Expand Down Expand Up @@ -753,3 +784,4 @@ _Please suggest more interesting projects._
[din99ode]: https://de.wikipedia.org/wiki/DIN99-Farbraum#Farbabstandsformel
[kotsarekno-ramos]: http://www.progmat.uaem.mx:8080/artVol2Num2/Articulo3Vol2Num2.pdf
[yiq]: https://en.wikipedia.org/wiki/YIQ
[css-images-4]: https://drafts.csswg.org/css-images-4/#color-stop-syntax
2 changes: 1 addition & 1 deletion benchmark/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"main": "index.js",
"license": "MIT",
"devDependencies": {
"chroma-js": "^1.4.0",
"chroma-js": "^2.0.3",
"d3-color": "^1.2.3",
"d3-interpolate": "^1.3.2",
"tinycolor2": "^1.4.1"
Expand Down
10 changes: 10 additions & 0 deletions benchmark/tests/interpolate-speed.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,16 @@ benchmark('culori: multiple colors in RGB', () => {
}
});

benchmark('culori: multiple colors in RGB (cached)', () => {
let lerp = culori.interpolate(colors);
for (var i = 0; i < iterations; i++) {
culori
.samples(count)
.map(lerp)
.map(hex);
}
});

let scale2 = chroma.scale(colors);
benchmark('chroma: multiple colors in RGB (cached)', () => {
for (var i = 0; i < iterations; i++) {
Expand Down
7 changes: 4 additions & 3 deletions benchmark/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
# yarn lockfile v1


chroma-js@^1.4.0:
version "1.4.0"
resolved "https://registry.yarnpkg.com/chroma-js/-/chroma-js-1.4.0.tgz#695c52e7c97617e5f687db31913503d410481ae4"
chroma-js@^2.0.3:
version "2.0.3"
resolved "https://registry.yarnpkg.com/chroma-js/-/chroma-js-2.0.3.tgz#2521d4f80c4e786e00064c4a62824e38ff6557c4"
integrity sha512-2kTvZZOFSV1O81/rm99t9vmkh9jQxsHqsRRoZevDVz/VCC3yKMyPuMK8M5yHG+UMg2tV6cRoqtZtgcD92udcBw==

d3-color@1:
version "1.0.3"
Expand Down
11 changes: 6 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
],
"devDependencies": {
"eslint": "^5.7.0",
"esm": "^3.2.22",
"gh-pages": "^2.0.1",
"husky": "^1.1.2",
"nyc": "^13.1.0",
Expand All @@ -45,12 +46,11 @@
},
"scripts": {
"build": "rollup -c",
"pretest": "yarn build",
"test": "tape test/*.js | tap-spec",
"test": "tape -r esm test/*.js | tap-spec",
"benchmark": "node benchmark/index.js",
"prepublishOnly": "yarn test",
"prepublishOnly": "yarn build && yarn test",
"coverage:report": "nyc report --reporter=lcov",
"coverage:test": "nyc --produce-source-map tape test/*.js | tap-spec",
"coverage:test": "nyc --produce-source-map tape -r esm test/*.js | tap-spec",
"docs:start": "hugo serve --source docs",
"docs:build": "hugo --source docs",
"docs:deploy": "yarn docs:build && gh-pages -d docs/public",
Expand All @@ -71,5 +71,6 @@
"jsxBracketSameLine": false,
"arrowParens": "avoid",
"printWidth": 80
}
},
"dependencies": {}
}
57 changes: 54 additions & 3 deletions src/interpolate/interpolate.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,37 @@
import converter from '../converter';
import { getModeDefinition } from '../modes';
import normalizePositions from '../util/normalizePositions';
import samples from '../samples';

// Color interpolation hint exponential function
let hint = (P, H) =>
H === 0 ? 1 : H === 1 ? 0 : Math.pow(P, Math.log(0.5) / Math.log(H));

export default (colors, mode = 'rgb', interpolations) => {
let def = getModeDefinition(mode);
let conv = converter(mode);

let conv_colors = [];
let positions = [];
let fns = {};

colors.forEach(val => {
if (Array.isArray(val)) {
conv_colors.push(conv(val[0]));
positions.push(val[1]);
} else if (typeof val === 'number' || typeof val === 'function') {
// Color interpolation hint or easing function
fns[positions.length] = val;
} else {
conv_colors.push(conv(val));
positions.push(undefined);
}
});

let converted = colors.map(converter(mode));
normalizePositions(positions);

let zipped = def.channels.reduce((res, channel) => {
res[channel] = converted.map(color => color[channel]);
res[channel] = conv_colors.map(color => color[channel]);
return res;
}, {});

Expand All @@ -24,13 +48,40 @@ export default (colors, mode = 'rgb', interpolations) => {
}
);

let n = conv_colors.length - 1;

return t => {
// clamp t to the [0, 1] interval
t = Math.min(Math.max(0, t), 1);

if (t <= positions[0]) {
return conv_colors[0];
}

if (t > positions[n]) {
return conv_colors[n];
}

// Convert `t` from [0, 1] to `t0` between the appropriate two colors.
// First, look for the two colors between which `t` is located.
// Note: this can be optimized by searching for the index
// through bisection instead of start-to-end.
let idx = 0;
while (positions[idx] < t) idx++;
let start = positions[idx - 1];
let delta = positions[idx] - start;

let P = (t - start) / delta;
let fn = fns[idx];
if (fn !== undefined) {
P = typeof fn === 'number' ? hint(P, (fn - start) / delta) : fn(P);
}

let t0 = (idx - 1 + P) / n;

return def.channels.reduce(
(res, channel) => {
let val = interpolators[channel](t);
let val = interpolators[channel](t0);
if (val !== undefined) {
res[channel] = val;
}
Expand Down
51 changes: 51 additions & 0 deletions src/util/normalizePositions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
Normalize an array of color stop positions for a gradient
based on the rules defined in the CSS Images Module 4 spec:

1. make the first position 0 and the last position 1 if missing
2. sequences of unpositioned color stops should be spread out evenly
3. no position can be smaller than any of the ones preceding it

Reference: https://drafts.csswg.org/css-images-4/#color-stop-fixup

Note: this method does not make a defensive copy of the array
it receives as argument. Instead, it adjusts the values in-place.
*/
export default arr => {
// 1. fix up first/last position if missing
if (arr[0] === undefined) {
arr[0] = 0;
}
if (arr[arr.length - 1] === undefined) {
arr[arr.length - 1] = 1;
}

let i = 1;
let j;
let from_idx;
let from_pos;
let inc;
while (i < arr.length) {
// 2. fill up undefined positions
if (arr[i] === undefined) {
from_idx = i;
from_pos = arr[i - 1];
j = i;

// find end of `undefined` sequence...
while (arr[j] === undefined) j++;

// ...and add evenly-spread positions
inc = (arr[j] - from_pos) / (j - i + 1);
while (i < j) {
arr[i] = from_pos + (i + 1 - from_idx) * inc;
i++;
}
} else if (arr[i] < arr[i - 1]) {
// 3. make positions increase
arr[i] = arr[i - 1];
}
i++;
}
return arr;
};
6 changes: 2 additions & 4 deletions test/blend.test.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
let tape = require('tape');
let culori = require('../');

let { blend } = culori;
import tape from 'tape';
import { blend } from '../src/index';

tape('blendNormal', function(test) {
test.deepEqual(blend(['white', 'rgba(0, 0, 0, 0.5)']), {
Expand Down
12 changes: 6 additions & 6 deletions test/clamp.test.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
let tape = require('tape');
let culori = require('../');
import tape from 'tape';
import { clamp } from '../src/index';

let clamp = culori.clamp('lch');
let _clamp = clamp('lch');

tape('RGB', function(test) {
test.deepEqual(clamp('red'), { mode: 'rgb', r: 1, g: 0, b: 0 });
test.deepEqual(_clamp('red'), { mode: 'rgb', r: 1, g: 0, b: 0 });

test.deepEqual(clamp('rgb(300, 255, 255)'), {
test.deepEqual(_clamp('rgb(300, 255, 255)'), {
mode: 'rgb',
r: 1,
g: 1,
Expand All @@ -17,7 +17,7 @@ tape('RGB', function(test) {
});

tape('LCh', function(test) {
test.deepEqual(clamp('lch(50 120 5)'), {
test.deepEqual(_clamp('lch(50 120 5)'), {
mode: 'lch',
l: 50,
c: 77.48291015625,
Expand Down
5 changes: 2 additions & 3 deletions test/css.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
let tape = require('tape');
let culori = require('../');
let { formatter, rgb } = culori;
import tape from 'tape';
import { formatter, rgb } from '../src/index';

tape('formatter()', function(test) {
test.deepEqual(
Expand Down
4 changes: 1 addition & 3 deletions test/cubehelix.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
let tape = require('tape');
// let culori = require('../');
// let { cubehelix, rgb } = culori;
import tape from 'tape';

tape('RGB -> Cubehelix', function(test) {
// test.deepEqual(
Expand Down
7 changes: 3 additions & 4 deletions test/difference.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
let tape = require('tape');
let culori = require('../');
let {
import tape from 'tape';
import {
differenceEuclidean,
differenceCie76,
differenceCie94,
Expand All @@ -11,7 +10,7 @@ let {
lab,
round,
hsl
} = culori;
} from '../src/index';

tape('euclidean distance in RGB', function(test) {
let delta = differenceEuclidean();
Expand Down
16 changes: 8 additions & 8 deletions test/displayable.test.js
Original file line number Diff line number Diff line change
@@ -1,28 +1,28 @@
let tape = require('tape');
let culori = require('../');
import tape from 'tape';
import { displayable } from '../src/index';

tape('RGB', function(test) {
test.equal(culori.displayable({ mode: 'rgb', r: 0, g: 0, b: 0 }), true);
test.equal(displayable({ mode: 'rgb', r: 0, g: 0, b: 0 }), true);

test.equal(
culori.displayable({ mode: 'rgb', r: 1, g: 1, b: 1, alpha: 0.5 }),
displayable({ mode: 'rgb', r: 1, g: 1, b: 1, alpha: 0.5 }),
true
);

test.equal(
culori.displayable({ mode: 'rgb', r: 1.1, g: 1, b: 1, alpha: 0.5 }),
displayable({ mode: 'rgb', r: 1.1, g: 1, b: 1, alpha: 0.5 }),
false
);

test.end();
});

tape('LCh', function(test) {
test.equal(culori.displayable('lch(50 0 0)'), true);
test.equal(displayable('lch(50 0 0)'), true);

test.equal(culori.displayable('lch(50 -100 0)'), true);
test.equal(displayable('lch(50 -100 0)'), true);

test.equal(culori.displayable('lch(120 -100 0)'), false);
test.equal(displayable('lch(120 -100 0)'), false);

test.end();
});
Loading