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);
}