nearest-color
Find the nearest color from a palette.
Given a target color and a list of available colors, nearest-color returns the closest
one by Euclidean distance in RGB space — handy for snapping arbitrary colors to a theme
palette, naming colors, or quantizing. Colors are given as hex (#f00, #ff0000),
rgb(…) strings, or any of the 17 standard CSS color names.
A faithful Rust port of the nearest-color
npm package.
- Zero dependencies
- Differential-tested against the reference
nearest-colorimplementation
Install
[]
= "0.1"
Usage
Build a reusable matcher from a named palette and get rich match info:
use ;
let palette = from_named.unwrap;
let m = palette.nearest.unwrap.unwrap;
assert_eq!;
assert_eq!;
assert_eq!;
// `m.distance` is the Euclidean RGB distance (≈119.0 here).
From an unnamed palette (or the built-in rainbow defaults), the match's name is
None and value is the nearest color's source:
use ;
let bg = from_colors.unwrap;
assert_eq!;
assert_eq!;
// `nearest_color` uses the default rainbow palette.
assert_eq!;
Combine palettes with [Matcher::or]:
use Matcher;
let a = from_named.unwrap;
let b = from_colors.unwrap;
let any = a.or;
assert_eq!;
Color parsing
[parse_color] accepts:
- Hex —
#fff,fff,#04fbc8(3 or 6 digits, with or without#, any case). rgb(…)—rgb(3, 10, 100)orrgb(50%, 0%, 50%)(percentages are rounded).- Standard CSS names — the 17 in [
STANDARD_COLORS] (red,aqua,gray, …).
Anything else returns an error (the matcher builders and nearest propagate it).
Contributors ✨
This project follows the all-contributors specification. Contributions of any kind are welcome — code, docs, bug reports, ideas, reviews! See the emoji key for how each contribution is recognized, and open a PR or issue to get involved.
Thanks goes to these wonderful people:
License
Licensed under either of MIT or Apache-2.0 at your option.