14

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.

Matthew
  • 143
  • 1
  • 1
  • 4
  • I like @rsp's answer (+1'ed) but wanted to mention that the Prefuse/Flare visualization libraries use the term Encoder to describe functionality that translates data into a visual attribute (like Color: ColorEncoder): http://flare.prefuse.org/api/flare/vis/operator/encoder/ColorEncoder.html Not sure how standardized that is across the field... – peteorpeter Feb 28 '11 at 03:45
  • I changed my example to use the HSL color model which makes it much simpler and better looking. – rsp Feb 28 '11 at 04:04

3 Answers3

17

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.

rsp
  • 107,747
  • 29
  • 201
  • 177
  • I'm not sure what the range of 240 is about. When I tested this in Chrome, it was expecting the first argument of the `hsl` function to be an angle in degrees, ranging from 0 to 360. – Jim Pivarski May 09 '14 at 06:27
  • 2
    @JimPivarski - Matthew was asking about a rainbow from red to blue and blue is 240 degrees in HSL. 360 degrees would be back to red again which was not what was asked in the question. – rsp Jul 02 '14 at 21:23
8

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 + ')';
}
wenqiang
  • 954
  • 1
  • 5
  • 14
2

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%)';
               }
f0ster
  • 549
  • 3
  • 12