Generate colors between red and green for an input range [duplicate]

You’re getting the muddled green because of the way you’re creating your gradient in RBG space. To get a “cleaner” gradient, you can use the HSV model as mentioned in the answer of the question you linked to.

RGB gradient (top) vs HSV (bottom)
top gradient uses RGB, bottom uses HSV

By scaling the H (hue) value between 0 (red) and 120 (green) you’ll get a nice clean transition. However, at the mid point (60) you’ll end up with bright yellow instead of your intended white. You can address this by modifying the S (saturation) value — at 0 saturation, you’ll end up with white (1 gives you full colour saturation.

Here’s a crude example which scales the saturation from 1 to 0 and back to 1 as the input value goes from 0 to 50 to 100 – http://jsfiddle.net/xgJ2e/2/

var hue = Math.floor((100 - val) * 120 / 100);  // go from green to red
var saturation = Math.abs(val - 50)/50;   // fade to white as it approaches 50

p.s. Converting between colour models is easy using jquery-colors, although it’s not too hard to roll your own.

Leave a Comment