0

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/

Kim T
  • 5,770
  • 1
  • 52
  • 79

1 Answers1

1

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);
}
MaxArt
  • 22,200
  • 10
  • 82
  • 81
  • nice this works much better! however the colours are a little off: http://jsfiddle.net/kmturley/sT8BL/2/ – Kim T Apr 28 '14 at 14:28
  • @KimT I see... I guess it may be because you chose green as the intermediate color, while yellow could have been a better choice. But to do so you have to modify the way you compute `r`, `g` and `b`... which will make you wonder if HSL isn't better. You can still convert the values to RGB, you know. – MaxArt Apr 28 '14 at 16:02
  • yeah maybe I do that, the HSL to RGB function is a little bit hefty http://stackoverflow.com/questions/2353211/hsl-to-rgb-color-conversion – Kim T Apr 28 '14 at 21:32
  • @KimT Cool, I posted a [more compact](http://stackoverflow.com/a/17338858/714240) version some months ago, if you want to give it a try. – MaxArt Apr 28 '14 at 22:56