你如何获得#xxxxxx 颜色的色调? [英] How do you get the hue of a #xxxxxx colour?
问题描述
如何提取以 #rrggbb
给出的颜色的色调分量?
How do you extract the hue component of a color given as #rrggbb
?
推荐答案
如果你搜索有关如何将 RGB 转换为 HSL,您会找到许多算法,包括在 谢尔盖.
If you search for how to convert RGB to HSL, you'll find a number of algorithms, including in the Wikipedia article linked by Sergey.
首先,提取十六进制颜色表示法的 RGB 分量.
First, extract the RGB components of the hex color notation.
var color='#c7d92c'; // A nice shade of green.
var r = parseInt(color.substr(1,2), 16); // Grab the hex representation of red (chars 1-2) and convert to decimal (base 10).
var g = parseInt(color.substr(3,2), 16);
var b = parseInt(color.substr(5,2), 16);
这将为您提供颜色的字节 (0-255) 表示.在本例中为 199、217、44.
That'll get you the byte (0-255) representation of your color. In this case, 199, 217, 44.
然后你可以使用维基百科文章中的公式来计算色调,或者无耻地窃取别人的代码:
You can then use the formulae from the Wikipedia article to calculate hue, or shamelessly steal someone else's code:
function rgbToHsl(r, g, b){
r /= 255, g /= 255, b /= 255;
var max = Math.max(r, g, b), min = Math.min(r, g, b);
var h, s, l = (max + min) / 2;
if(max == min){
h = s = 0; // achromatic
}else{
var d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch(max){
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
return [h, s, l];
}
(请参阅源页面以获取文档和hslToRgb()代码>函数.)
(See the source page for documentation and a hslToRgb()
function.)
我们现在可以将这两个片段放在一起并获得色调:
We can now put those two snippets together and get the hue:
var hue = rgbToHsl(r, g, b)[0] * 360;
[0]
是抓取色调–该函数返回一个数组 ([h,s,l]
).我们乘以 360,因为色调返回为 0 到 1 之间的值;我们想把它转换成度数.
The [0]
is to grab the hue – the function returns an array ([h,s,l]
). We multiply by 360 since hue is returned as a value between 0 and 1; we want to convert it to degrees.
使用 #c7d92c
的示例颜色,hue
将为 ~66.24.Photoshop 的颜色选择器显示该颜色的色调为 66°.所以看起来我们很好!
With the example color of #c7d92c
, hue
will be ~66.24. Photoshop's color picker says the hue of that color is 66° so it looks like we're good!
这篇关于你如何获得#xxxxxx 颜色的色调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!