Alex Rivera | Logout

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

Asked 2011-02-28T03:04:31.723
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.

Edit
Report

1 Answer

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%)';
               }
answered 2013-03-26T19:24:27.920

Your Answer