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
This is what I came up with:
function rgbify(maxval, minval, val, moreisgood) {
var intnsty = (val - minval) / (maxval - minval);
var r, g;
if (moreisgood) {
if (intnsty > 0.5) {
g = 255;
r = Math.round(2 * (1 - intnsty) * 255);
} else {
r = 255;
g = Math.round(2 * intnsty * 255);
}
} else { //lessisgood
if (intnsty > 0.5) {
r = 255;
g = Math.round(2 * (1 - intnsty) * 255);
} else {
g = 255;
r = Math.round(2 * intnsty * 255);
}
}
return "rgb(" + r.toString() + ", " + g.toString() + ", 0)";
}
jsfiddle
The moreisgood flag toggles if higher values should be red or green.
maxval and minval are the threshold values for your range.
val is the value to be converted to rgb