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 • 2.09 kB
JavaScript
;var colorUtils_js=require('./color-utils.js'),common_js=require('./common.js'),G=require('./data/colorSet.js'),hexUtils_js=require('./hex-utils.js'),hslUtils_js=require('./hsl-utils.js'),rgbUtils_js=require('./rgb-utils.js');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var G__default=/*#__PURE__*/_interopDefault(G);const I=[{regex:common_js.hexRegex,parser:hexUtils_js.parseHex,converter:hexUtils_js.hexToRgb},{regex:common_js.rgbRegex,parser:rgbUtils_js.parseRgb,converter:rgbUtils_js.getRgbValues},{regex:common_js.hslRegex,parser:hslUtils_js.parseHsl,converter:hslUtils_js.hslToRgb}],a=new Map;function u(e,r=G__default.default,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={...colorUtils_js.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,common_js.BLACKANDWHITE).name==="white"}function N(e){return u(e,common_js.BLACKANDWHITE).name==="black"}function V(e){return u(e,common_js.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(common_js.rgbRegex.test(e)){const r=rgbUtils_js.parseRgb(e),o=rgbUtils_js.getRgbValues(r);return hexUtils_js.valuesToHex(o)}throw new Error(`Invalid color: ${e}`)}Object.defineProperty(exports,"getColor",{enumerable:true,get:function(){return colorUtils_js.getColor}});Object.defineProperty(exports,"getColors",{enumerable:true,get:function(){return colorUtils_js.getColors}});exports.closest=u;exports.closestRGB=V;exports.colorParsers=I;exports.distance=C;exports.isDark=N;exports.isLight=H;exports.parseColor=v;exports.rgbToHex=$;