【问题标题】:How would u be able to tell if a color is red or blue ... tinted (Javascript)你怎么能知道颜色是红色还是蓝色......有色(Javascript)
【发布时间】:2021-01-16 02:20:28
【问题描述】:

假设我给你一个十六进制颜色#f9090 你将如何确定这种颜色是否是橙色的?

如果以前是不可能的,那么它是否可以使用 RGB 值?

const coloTint = getColorTint('#f90')
/* should log 'orange' 

【问题讨论】:

  • 十六进制颜色代码基本上只是一个数字,以 16 为基数表示。您可以简单地定义您认为是“橙色”的一个或多个数字范围,并测试该数字是否在该范围内......
  • 也应该将#f91 标记为橙色吗?如果是,则需要将 RGB 颜色转换为 HSL 并检查 H-Value
  • 你对“红色”的定义是什么?
  • 例如血是红色的?它应该能够简单地说它是红色还是黄色还是蓝色......问题很简单,但实现它的方法似乎很困难,我喜欢为颜色组预定义范围的想法然后只是检查值是否介于两者之间
  • 我从来没有在 JS 中做过这种事情,但你可能想看看 HSV 颜色空间,一旦你了解它是如何工作的,这样的一些答案可能会有所帮助:stackoverflow.com/questions/8022885/…

标签: javascript


【解决方案1】:

如果您将十六进制代码转换为 hsv 并使用 lookup table 将色调值映射到颜色名称,这将非常简单。

请注意,使用此逻辑,十六进制代码的名称不会是橙色,而是红色。要获得橙色结果,您的颜色需要至少 30° 的色调值 (#f9c000)

如果您需要橙色作为该值,您可以调整查找表以满足您的需要。

(如果翻译不正确,请原谅。我只是将表格粘贴到谷歌翻译中)

const hex = '#f90900';
const name = hex2name(hex);
console.log (`Name of '${hex}' is '${name}'`);


const orangeHSV = [30, 1, 249];
const orangeRGB = hsv2rgb(...orangeHSV);
const orangeHEX = rgb2hex(...orangeRGB);
console.log (`hex for first orange value is '${orangeHEX}'`);

const test = hex2name(orangeHEX);
console.log (`Test if ${orangeHEX} yields orange: ${test}`)
<script>
// https://stackoverflow.com/a/54024653/1487756
function hsv2rgb(h,s,v) {                              
  let f= (n,k=(n+h/60)%6) => v - v*s*Math.max( Math.min(k,4-k,1), 0);     
  return [f(5),f(3),f(1)];       
}   

// https://stackoverflow.com/a/54070620/1487756
function rgb2hsv(r,g,b) {
  let v=Math.max(r,g,b), n=v-Math.min(r,g,b);
  let h= n && ((v==r) ? (g-b)/n : ((v==g) ? 2+(b-r)/n : 4+(r-g)/n)); 
  return [60*(h<0?h+6:h), v&&n/v, v];
} 

const clrLkp = [["red", 0],["vermilion", 15],["brown", 20],["orange", 30],["safran", 45],["yellow", 60],["light green yellow", 75],["green yellow", 90],["limett", 105],["dark green", 120],["green", 120],["light blue-green", 135],["blue green", 150],["green cyan", 165],["cyan", 180],["blaucyan", 195],["green blue", 210],["light green blue", 225],["blue", 240],["indigo", 255],["violet", 270],["blue magenta", 285],["magenta", 300],["red magenta", 315],["blue red", 330],["light blue red", 345]].reverse()

const hex2rgb = hex => {
    const parts = hex.slice(1).match(/../g);
    if (!parts || parts.length <3) throw new Error('Invalid hex value');
    const dec = parts.map(p => parseInt(p, 16));
    return dec;
}
const hsv2name = (h,s,v) => clrLkp.find(([clr,val]) => h >= val)[0];
const hex2name = hex => [hex2rgb, rgb2hsv, hsv2name].reduce((a,v) => v(...[a].flat()),hex);

const pad = v => (v+'0').slice(0,2);
const rgb2hex = (r,g,b) => '#' + [r,g,b].map(Math.round).map(n => pad(n.toString(16))).join('');
</script>

【讨论】:

    猜你喜欢
    • 2018-12-31
    • 2011-09-18
    • 2011-09-22
    • 2020-10-14
    • 2013-02-05
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    • 2015-03-09
    相关资源
    最近更新 更多