Map value to color scale

后端 未结 5 900
执念已碎
执念已碎 2021-01-18 11:13

I have a list of values which should be plotted to a map with a certain color. The plotting to the map is already done, but I need to figure out a way to map the value

5条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-18 11:34

    The other answer was very usefull. I decided to use JS as it reduces server load. The requirements also changed. The bar has to go from Red to white in the middle and then from white to yellow. And if the value is 0 it should be black. Here is my code for anyone who ever encounters a similar situation.

    var normalize_base = 2*255;
    var no_con_color = "black";
    
    function decimalToHex(d, padding) {
        var hex = Number(d).toString(16);
        padding = typeof (padding) === "undefined" || padding === null ? padding = 2 : padding;
    
        while (hex.length < padding) {
            hex = "0" + hex;
    }
    
        return hex;
    }
    
    function normalize(max, min, value)
    {
         var normalized = (value - min) / (max - min) ;
         return Math.floor(normalized * normalize_base);
    }
    
    function value2Color(value)
    {
        if(value <= 0 || value == undefined)
        {
            return no_con_color;
        }
        var g = 0;
        var b = 0;
        var r = 0;
        if(value < 255)
        {
            r = 255;
            g = value;
            b = value;
        } else {
            r = (2*255) - value;
            g = 255;
            b = (2*255) - value;
        }  
    
        return "#" + decimalToHex(r) + decimalToHex(g) +  decimalToHex(b);
    }
    

提交回复
热议问题