from green to red color depend on percentage

前端 未结 14 2030
北恋
北恋 2020-11-30 20:00

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

14条回答
  •  自闭症患者
    2020-11-30 20:52

    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

提交回复
热议问题