繁体   English   中英

如何将颜色转换为 rgb 值

[英]How do I convert a color to an rgb value

我正在尝试将背景颜色与 javascript 中的字体颜色相反,如下所示:

let search_bar_bgColor = document.getElementById("search_bgColor").value;
let search_bar_color = search_bar_bgColor.invert();

但是用户可以键入从 colors 到 rgb 值的任何内容,我如何将用户输入转换为与自身完全相反的值?

做这样的事情:

function invert(color) {
  let values = color.split(', ')

  for (i = 0; i < 3; i++) {
    let inverted = 255 - values[i] //Invert color by subtracting 255 from RGB value
    console.log(inverted);
  }
}

invert('255, 0, 0')

我相信您可以很容易地使用您的输入值进行设置。

通过“相反”,我假设你的意思是最对比

没有内置方法可以执行此操作,因此您必须自己使用 devise,这并不简单。

第一步是准确定义什么是相反的颜色。 这里有讨论: How to pick good contrast RGB colors programmatically?

一旦你决定了一个程序来实现你想要的,你就需要创建一个 function 来转换颜色。 为了简化算法,传递并返回到 function 的颜色将表示 rgb() 颜色(现在不用担心用户输入的颜色格式)。

一个这样的 function,基于在 Adobe Illustrator 中选择对比色的方法(在我上面发布的链接中 Kyle Rosenbluth 的回答中讨论过),可能看起来像这样:

function contrastingColour(red,green,blue) {
  // find the highest and lowest channel number and sum them;
  const colorArray = [parseInt(red),parseInt(green),parseInt(blue)];
  colorArray.sort((a, b) => a - b);
  sumOfBrightestAndDimestChannel = colorArray[0] + colorArray[2];

  let redChannel = sumOfBrightestAndDimestChannel - red;
  let greenChannel = sumOfBrightestAndDimestChannel - green;
  let blueChannel = sumOfBrightestAndDimestChannel - blue; 

  return `rgb(${redChannel},${greenChannel},${blueChannel})`;
} 

为了将 function 应用于用户输入,您必须将用户的颜色格式转换为红色、绿色和蓝色的值。 如果您希望用户简单地在输入中键入一些内容,这将充满困难,因为您将不得不详尽地筛选和转换每个条目。

更好的方法是限制用户提交颜色的方式,允许他们完全选择 rgb colors、hex colors 和 named colors。

对于 rgb 颜色,为它们呈现三个下拉菜单,以编程方式加载每列的每个选项 0-255。

同样,十六进制颜色的三个下拉菜单可以将选择限制在 00 到 ff 范围内。

对于命名的颜色,可以从每个命名的 web 颜色的可用列表中以编程方式构建网络安全颜色的下拉列表,例如https://gist.github.com/bobspace/2712980最后,您需要定义函数来转换十六进制和将颜色命名为 rgb,以便您可以在 function 中处理它们。

祝你好运。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM