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

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

    A possible solution would be to convert your color from RGB to HSB. HSB stands for hue, saturation, and brightness (also known as HSV, where V is for value). Then you have just one parameter to check: brightness.

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
提交回复
热议问题