问题
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?
回答1:
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
来源:https://stackoverflow.com/questions/40110721/generate-gradient-step-based-on-dynamic-value-including-decimals