Search code examples
javascriptjquerycsshsl

Generate gradient step based on dynamic value, including decimals


Based on this question, which has a fabulous answer for values from 0..1, I tried to modify the function to include the min and max values.

function getColor(value, min, max){
    var hue=((max-(value-min))*120).toString(10);
    return ["hsl(",hue,",100%,50%)"].join("");
}

It seems to work fine for whole numbers, but not so much for decimals. For instance, these work as expected:

var value=42;
var d=document.createElement('div');
d.textContent="value="+value + " (this should be green)";
d.style.backgroundColor=getColor(value,42,100);
document.body.appendChild(d);

var value=42;
var d=document.createElement('div');
d.textContent="value="+value + " (this should be red)";
d.style.backgroundColor=getColor(value,0,42);
document.body.appendChild(d);

But these do not:

var value=0.1;
var d=document.createElement('div');
d.textContent="value="+value + " (this should be green)";
d.style.backgroundColor=getColor(value,0,90);
document.body.appendChild(d);

var value=0.1;
var d=document.createElement('div');
d.textContent="value="+value + " (this should be green)";
d.style.backgroundColor=getColor(value,0,5);
document.body.appendChild(d);

The last one is actually blue... Here is a fiddle. How can I change this to work with all 4 scenarios?


Solution

  • This seems to work very well:

    function getColor(value, min, max){
        if (value > max) value = max;
        var v = (value-min) / (max-min);
        var hue=((1 - v)*120).toString(10);
        return ["hsl(",hue,",100%,50%)"].join("");
    }
    

    edit: adjusted based on comments below