Automatically change text color to assure readability

前端 未结 8 2030
生来不讨喜
生来不讨喜 2020-12-08 00:42

Users can set the background-color of a button through a textbox that accept RGB hexadecimal notation: ff00ff, ccaa22, etc. So I need to set the te

8条回答
  •  既然无缘
    2020-12-08 01:45

    I had the same issue once, and gathered information all over the internet also using Salman A answer, I came up with this function, it supports hex, rgb and rgba

    var invertColor = function (color) {
                var hex   = '#';
                if(color.indexOf(hex) > -1){
                    color = color.substring(1);           
                    color = parseInt(color, 16);         
                    color = 0xFFFFFF ^ color;            
                    color = color.toString(16);           
                    color = ("000000" + color).slice(-6); 
                    color = "#" + color; 
                }else{
                    color = Array.prototype.join.call(arguments).match(/(-?[0-9\.]+)/g);
                    for (var i = 0; i < color.length; i++) {
                        color[i] = (i === 3 ? 1 : 255) - color[i];
                    }
                    if(color.length === 4){
                        color = "rgba("+color[0]+","+color[1]+","+color[2]+","+color[3]+")";
                    }else{
                        color = "rgb("+color[0]+","+color[1]+","+color[2]+")";
                    }
                }         
                return color;
            }
    

    but I don't think this is what you need, I found something more interesting, the below function will return white or black, it will decide witch one is more readable on the given color.

    var getContrastYIQ = function (color){
                var hex   = '#';
                var r,g,b;
                if(color.indexOf(hex) > -1){
                    r = parseInt(color.substr(0,2),16);
                    g = parseInt(color.substr(2,2),16);
                    b = parseInt(color.substr(4,2),16);
                }else{
                    color = color.match(/\d+/g);
                    r = color[0];
                    g = color[1];
                    b = color[2];
                }
    
                var yiq = ((r*299)+(g*587)+(b*114))/1000;
                return (yiq >= 128) ? 'black' : 'white';
            }
    

    I don't take credit for any of this, I just got inspired and modified to my needs.

    Sources: YIQ function explained

提交回复
热议问题