I have a poll system and I want answers for this poll to be colored. For example: If it\'s 10% it would be red, if 40% it would be yellow and if 80% it would be green, so I
Mattisdada's code was really helpful for me while I was making a chart to display statistics of some quiz results. I modified it a bit to allow "clipping" of the percentage (not sure what the right term is) and also to work both ways along the colour wheel, e.g. both from green(120) to red(0) and vice versa.
function pickColourByScale(percent, clip, saturation, start, end)
{
var a = (percent <= clip) ? 0 : (((percent - clip) / (100 - clip))),
b = Math.abs(end - start) * a,
c = (end > start) ? (start + b) : (start - b);
return 'hsl(' + c + ','+ saturation +'%,50%)';
}
Basically, by setting a percentage value to clip the scaling at, everything below that value will be coloured as your start colour. It also recalculates the scaling according to 100% - clip.
Let's go through an example scenario where I enter the following values:
end: 120 (green)
I end up with yellow, which is halfway between red and green. If I hadn't done the recalculation in step 1, I'd have ended up with a more greenish colour, which could be misleading.