nearest
nearest finds the closest color in a list of swatches or design tokens. It compares colors in OKLab by default and returns the index, so you can retrieve a label or token name from the original list.
Example
import { colore } from 'colore-js';
const match = colore('#7c3aed').nearest(['#f00', '#7b3ae8', '#0f0']);
match.color.css(); // '#7b3ae8'
match.index; // 1
match.distance.toFixed(4); // '0.0078'
Syntax
colore(target).nearest(
colors: (ColorInput | Color)[],
distanceFn?: (first: InternalColor, second: InternalColor) => number
): NearestResult
Parameters
Returns
Throws
An Error for an empty list, or a ColorError for invalid color input or a non-array candidate argument.
Match an imported color to a design token
import { colore } from 'colore-js';
const tokens = { inverse: '#fff', ink: '#000', muted: '#767676' };
const keys = Object.keys(tokens);
const token = colore('#777').nearest(Object.values(tokens));
keys[token.index]; // 'muted'
Related
- nearestNamed to search CSS color names
- deltaEOK for the default distance
- palette to build your own candidates