Average 2 hex colors together in javascript

后端 未结 8 2029
天命终不由人
天命终不由人 2021-01-31 20:13

Alright thought I would throw this one out there for the crowd to think over.

Given a function (written in javascript) that expects two strings

8条回答
  •  遇见更好的自我
    2021-01-31 20:38

    Here is my function, hope it helps.

    function averageColors( colorArray ){
        var red = 0, green = 0, blue = 0;
    
        for ( var i = 0; i < colorArray.length; i++ ){
            red += hexToR( "" + colorArray[ i ] + "" );
            green += hexToG( "" + colorArray[ i ] + "" );
            blue += hexToB( "" + colorArray[ i ] + "" );
        }
    
        //Average RGB
        red = (red/colorArray.length);
        green = (green/colorArray.length);
        blue = (blue/colorArray.length);
    
        console.log(red + ", " + green + ", " + blue);
        return new THREE.Color( "rgb("+ red +","+ green +","+ blue +")" );
    }
    
    //get the red of RGB from a hex value
    function hexToR(h) {return parseInt((cutHex( h )).substring( 0, 2 ), 16 )}
    
    //get the green of RGB from a hex value
    function hexToG(h) {return parseInt((cutHex( h )).substring( 2, 4 ), 16 )}
    
    //get the blue of RGB from a hex value
    function hexToB(h) {return parseInt((cutHex( h )).substring( 4, 6 ), 16 )}
    
    //cut the hex into pieces
    function cutHex(h) {if(h.charAt(1) == "x"){return h.substring( 2, 8 );} else {return h.substring(1,7);}}
    

提交回复
热议问题