Average 2 hex colors together in javascript

后端 未结 8 2025
天命终不由人
天命终不由人 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:29

    Here's a compact set of relevant (interdependent) functions:

    Hex ⟷ RGB Color Conversion:

    function hexToRgb(h){return['0x'+h[1]+h[2]|0,'0x'+h[3]+h[4]|0,'0x'+h[5]+h[6]|0]}
    function rgbToHex(r,g,b){return"#"+((1<<24)+(r<<16)+(g<<8)+ b).toString(16).slice(1);}
    

    Calculate Average of 2 Hex Colors: Requires conversion functions (above)

    function avgHex(h1,h2){a=hexToRgb(h1);b=hexToRgb(h2); return rgbToHex(~~((a[0]+b[0])/2),~~((a[1]+b[1])/2),~~((a[2]+b[2])/2));}
    

    Generate Random Hex Color:

    function rndHex(){return'#'+('00000'+(Math.random()*(1<<24)|0).toString(16)).slice(-6);}
    

    Run snippet for demo:

    // color functions (average/random/conversion)
    function hexToRgb(h){return['0x'+h[1]+h[2]|0,'0x'+h[3]+h[4]|0,'0x'+h[5]+h[6]|0]}
    function rgbToHex(r,g,b){return"#"+((1<<24)+(r<<16)+(g<<8)+ b).toString(16).slice(1);}
    function rndHex(){return'#'+('00000'+(Math.random()*(1<<24)|0).toString(16)).slice(-6);}
    function avgHex(h1,h2){a=hexToRgb(h1);b=hexToRgb(h2);return rgbToHex(~~((a[0]+b[0])/2),~~((a[1]+b[1])/2),~~((a[2]+b[2])/2));}
    
    //code below is just for the demo
    function auto(){if(chk.checked){tmr=setInterval(rnd,1000)}else{clearTimeout(tmr)}}auto();
    function rnd(go){for(h of[h1,h2]){h.value=rndHex();}avgInput();}
    addEventListener('input',avgInput); 
    function avgInput(){ // get avg & colorize
     ha.value=avgHex(h1.value,h2.value);
     for(h of [h1,h2,ha])h.style.background=h.value;
    }
    *{font-family:monospace;font-size:5vw; }



提交回复
热议问题