获取两种返回相同结果的十六进制颜色的平均值

时间:2018-10-04 07:54:05

标签: javascript

我有一段javascript试图获取两种十六进制颜色的平均值,但我一直得到相同的结果,即#000000

我一直凝视着,看不到答案,所以我希望有人能指出来

 const color1 = document.getElementById('Number1');
    const color2 = document.getElementById('Number2');

    // get the average color of two hex colors.
    function average(color1,color2){

        const avg  = function(a,b){ return (a+b)/2; };
        const t16  = function(c){ return parseInt((''+c).replace('#',''),16) };
        const hex  = function(c){ const t = (c>>0).toString(16);

        return t.length === 2 ? t : '0' + t },

            hex1 = t16(color1),
            hex2 = t16(color2),

            r    = function(hex){ return hex >> 16 & 0xFF},
            g    = function(hex){ return hex >> 8 & 0xFF},
            b    = function(hex){ return hex & 0xFF},

            output  = '#' + hex(avg(r(hex1),r(hex2)))
                + hex(avg(g(hex1),g(hex2)))
                + hex(avg(b(hex1),b(hex2)));

        console.log(output);


        document.getElementById('output').innerHTML=output ;

1 个答案:

答案 0 :(得分:0)

您调用了average函数吗?

function averageColor(color1,color2){
    var avg  = function(a,b){ return (a+b)/2; },
        t16  = function(c){ return parseInt((''+c).replace('#',''),16) },
        hex  = function(c){ var t = (c>>0).toString(16);
                           return t.length == 2 ? t : '0' + t },
        hex1 = t16(color1),
        hex2 = t16(color2),
        r    = function(hex){ return hex >> 16 & 0xFF},
        g    = function(hex){ return hex >> 8 & 0xFF},
        b    = function(hex){ return hex & 0xFF},
        res  = '#' + hex(avg(r(hex1),r(hex2))) 
                   + hex(avg(g(hex1),g(hex2))) 
                   + hex(avg(b(hex1),b(hex2)));
console.log(res);
    return res;
}

// e.g.
averageColor('#ffffff','#000000'); // "#7f7f7f"

签入console,希望它能起作用。