How to check if hex color is “too black”?

前端 未结 8 1634
谎友^
谎友^ 2020-12-04 05:21

I\'m trying to evaluate the darkness of a color chosen by a color picker to see if it\'s \"too black\", and if so, set it to white. I thought I could use the first character

8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-04 05:39

    This work with hex e.g #fefefe

    function isTooDark(hexcolor){
        var r = parseInt(hexcolor.substr(1,2),16);
        var g = parseInt(hexcolor.substr(3,2),16);
        var b = parseInt(hexcolor.substr(4,2),16);
        var yiq = ((r*299)+(g*587)+(b*114))/1000;
        // Return new color if to dark, else return the original
        return (yiq < 40) ? '#2980b9' : hexcolor;
    }
    

    You can change it to return true or false by change

    return (yiq < 40) ? '#2980b9' : hexcolor;
    

    to

    return (yiq < 40);
    

提交回复
热议问题