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

前端 未结 8 1608
谎友^
谎友^ 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:47

    I found this WooCommerce Wordpress PHP function (wc_hex_is_light) and I converted to JavaScript. Works fine!

    function wc_hex_is_light(color) {
        const hex = color.replace('#', '');
        const c_r = parseInt(hex.substr(0, 2), 16);
        const c_g = parseInt(hex.substr(2, 2), 16);
        const c_b = parseInt(hex.substr(4, 2), 16);
        const brightness = ((c_r * 299) + (c_g * 587) + (c_b * 114)) / 1000;
        return brightness > 155;
    }
    

提交回复
热议问题