color-2-name
Version:
Finds the closest color name to a given hex, rgb and hsl color (with and without alpha). It uses the Euclidean distance formula to calculate the distance between colors in the RGB color space
1 lines • 1.64 kB
JavaScript
import {getColor}from'./color-utils.js';export{getColor,getColors}from'./color-utils.js';import {hexRegex,rgbRegex,hslRegex,BLACKANDWHITE,RGBSET}from'./common.js';import G from'./data/colorSet.js';import {hexToRgb,parseHex,valuesToHex}from'./hex-utils.js';import {hslToRgb,parseHsl}from'./hsl-utils.js';import {getRgbValues,parseRgb}from'./rgb-utils.js';const I=[{regex:hexRegex,parser:parseHex,converter:hexToRgb},{regex:rgbRegex,parser:parseRgb,converter:getRgbValues},{regex:hslRegex,parser:parseHsl,converter:hslToRgb}],a=new Map;function u(e,r=G,o){const n=`${e}-${o!=null&&o.info?"info":"basic"}`;if(a.has(n))return a.get(n);let s=Number.MAX_SAFE_INTEGER;const t={name:"error",color:"#F00"};if(r.length<1)return t;const i=v(e),E=r.length;for(let l=0;l<E;l++){const c=r[l],R=C([i.r,i.g,i.b],c,true);if(R<s&&(s=R,t.name=c[3],t.color=`rgb(${c[0]},${c[1]},${c[2]})`),R===0)break}if(o!=null&&o.info){const c={...getColor(t.name,r),...t,gap:Math.sqrt(s)};return a.set(n,c),c}return a.set(n,t),t}function v(e){for(const{regex:r,parser:o,converter:n}of I)if(r.test(e)){const s=o(e);return n(s)}throw new Error(`Invalid color: ${e}`)}function H(e){return u(e,BLACKANDWHITE).name==="white"}function N(e){return u(e,BLACKANDWHITE).name==="black"}function V(e){return u(e,RGBSET).name}function C(e,r,o=false){const n=r[0]-e[0],s=r[1]-e[1],t=r[2]-e[2],i=n*n+s*s+t*t;return o?i:Math.sqrt(i)}function $(e){if(rgbRegex.test(e)){const r=parseRgb(e),o=getRgbValues(r);return valuesToHex(o)}throw new Error(`Invalid color: ${e}`)}export{u as closest,V as closestRGB,I as colorParsers,C as distance,N as isDark,H as isLight,v as parseColor,$ as rgbToHex};