Search code examples
javascripthexrgba

Automatic Hex rgb colour generation


I am generating heatmap style colours in JavaScript based on the values from cold to hot. But for some reason I am getting some pinks and some purples.

There are lots of answers on stackoverflow but they mostly relate to generating using HSL, and unfortunately for Google Earth I need RGBA format (backwards as ABGR)

1 = red = hot

0.5 = green = middle

0 = blue = cold

    function generateColor(value) {
        var r = Math.round(value * 255),
            g = Math.round((1 - Math.abs(0.5 - value)) * 255),
            b = Math.round((1 - value) * 255);
        r = r.toString(16);
        g = g.toString(16);
        b = b.toString(16);
        if (r.length < 2) {
            r += r;
        }
        if (g.length < 2) {
            g += g;
        }
        if (b.length < 2) {
            b += b;
        }
        return 'ff' + b + g + r;
    }

There's a bug in here somewhere!! Here's a fiddle I've been using to try and work out the problem:

http://jsfiddle.net/kmturley/sT8BL/1/


Solution

  • I think your problem is here:

    if (r.length < 2) {
        r += r;
    }
    

    If r is just one character, add a 0, not itself to it:

    if (r.length < 2) {
        r = "0" + r;
    }
    

    In just one line:

    r = ("0" + r.toString(16)).slice(-2);
    

    But you can also put most of the function in just a line:

    function generateColor(value) {
        var r = Math.round(value * 255),
            g = Math.round((1 - Math.abs(0.5 - value)) * 255),
            b = Math.round((1 - value) * 255);
        return (0xff000000 + 0x10000 * b + 256 * g + r).toString(16);
    }