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.
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 + ')';
}
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.
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%)';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With