Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
456 views
in Technique[技术] by (71.8m points)

javascript - How do you get the hue of a #xxxxxx colour?

How do you extract the hue component of a color given as #rrggbb?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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);

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];
}

(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;

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.

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...