Javascript: convert grayscale to hue

I have a grayscale color, rgb (128, 128, 128), and I want to find a color in a specific color, 0 (red), which has the same brightness as gray in Javascript.

I know how to find the lightness of gray using ((0.3 * r + 0.59 * g + 0.11 * b)), but I want to know how I could add a hue to this color. I want white to become white, light gray to become light red, medium gray to become bright red, dark gray to become dark red, and black to black, etc. Shade may change.

Currently I tried this, but it gives a bright red, not white when given white.

// lightness = 0 - 255
// color = {r: 1, g: 0, b: 0}

newcolor = {};
newcolor.r = lightness * color.r;
newcolor.g = lightness * color.g;
newcolor.b = lightness * color.b;
return newcolor;
+4
source share
1

HSV HSL RGB, , .

, HSL HSV, HSV (, ). , HSL .

HSV ( )

HSV ( ) , , , , , (HSL , . ).

, [0, 100]. [0, 200]. , , :

if (lum > 100) {
    col = hsv2rgb(angle, 100 - (lum - 100), 100);
} else {
    col = hsv2rgb(angle, 100, lum);    
}

.

lum, . [0, 255]:

lum = luma / 255 * 200;

HSV

HSL ( )

HSL, , (), , HSV , . HSV HSL.

HSL :

HSL

Demo image

, , , , ( HSV +, -, ).

, , HSL RGB:

function hsl2rgb(h, s, l) {

    var r, g, b, q, p;

    if (s == 0) {
        r = g = b = l;
    } else {
        function hue2rgb(p, q, t) {
            if (t < 0) t++;
            if (t > 1) t--;
            if (t < 1/6) return p + (q - p) * 6 * t;
            if (t < 1/2) return q;
            if (t < 2/3) return p + (q - p) * (2/3 - t) * 6;
            return p;
        }

        q = l < 0.5 ? l * (1 + s) : l + s - l * s;
        p = 2 * l - q;

        r = hue2rgb(p, q, h + 1/3);
        g = hue2rgb(p, q, h);
        b = hue2rgb(p, q, h - 1/3);
    }

    return {
        r: r * 255,
        g: g * 255,
        b: b * 255};
}
+3

All Articles