Generate gradient step based on dynamic value, including decimals

三世轮回 提交于 2020-01-07 05:45:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!