| 1 |
import ColorSpace from "./ColorSpace.js"; |
| 2 |
import { isNone } from "./util.js"; |
| 3 |
|
| 4 |
/** @import { ColorTypes } from "./types.js" */ |
| 5 |
|
| 6 |
/** |
| 7 |
* Euclidean distance of colors in an arbitrary color space |
| 8 |
* @param {ColorTypes} color1 |
| 9 |
* @param {ColorTypes} color2 |
| 10 |
* @param {string | ColorSpace} space |
| 11 |
* @returns {number} |
| 12 |
*/ |
| 13 |
export default function distance (color1, color2, space = "lab") { |
| 14 |
space = ColorSpace.get(space); |
| 15 |
|
| 16 |
// Assume getColor() is called on color in space.from() |
| 17 |
let coords1 = space.from(color1); |
| 18 |
let coords2 = space.from(color2); |
| 19 |
|
| 20 |
return Math.sqrt( |
| 21 |
coords1.reduce((acc, c1, i) => { |
| 22 |
let c2 = coords2[i]; |
| 23 |
if (isNone(c1) || isNone(c2)) { |
| 24 |
return acc; |
| 25 |
} |
| 26 |
|
| 27 |
return acc + (c2 - c1) ** 2; |
| 28 |
}, 0), |
| 29 |
); |
| 30 |
} |