Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map a range of values (e.g. [0,255]) to a range of colours (e.g. rainbow: [red,blue]) in JavaScript

I'm sure this must be a fairly straightforward, but it's a difficult question to word. I don't even know what to google for.

I'm not looking for any complicated solution. Basically, I'm drawing lines on a Canvas, and I want different colours depending on the length of the line. Usually I just scale, say, the red channel (#ff0000 * (length of line)/(maximum line length)), but this solution isn't ideal. I'm just looking for an equation that will give me a #rrggbb value for a certain position on a rainbow gradient, if that makes sense.

Thank you to whoever can help with this! It's very much appreciated.

like image 636
Matthew Avatar asked Feb 28 '11 03:02

Matthew


3 Answers

This article describes a method to make rainbow colors in JS. Basically it uses the Sine function to make rainbow colors. In short, the equation you need is something like this. See DEMO.

function RainBowColor(length, maxLength)
{
    var i = (length * 255 / maxLength);
    var r = Math.round(Math.sin(0.024 * i + 0) * 127 + 128);
    var g = Math.round(Math.sin(0.024 * i + 2) * 127 + 128);
    var b = Math.round(Math.sin(0.024 * i + 4) * 127 + 128);
    return 'rgb(' + r + ',' + g + ',' + b + ')';
}
like image 189
wenqiang Avatar answered Nov 14 '22 07:11

wenqiang


Since you're using canvas then you can probably use the HSL color space (correct me if I'm wrong). It would make the code much simpler:

function rainbow(n) {
    n = n * 240 / 255;
    return 'hsl(' + n + ',100%,50%)';
}

If you're ok with having your range from 0 to 240 then you can even remove the first line of this function. See DEMO.

like image 26
rsp Avatar answered Nov 14 '22 07:11

rsp


I ended up using something similar to @rsp 's answer

                var getColorAtScalar = function (n, maxLength) {
                    var n = n * 240 / (maxLength);
                    return 'hsl(' + n + ',100%,50%)';
               }
like image 2
f0ster Avatar answered Nov 14 '22 08:11

f0ster