Dynamically change the text color based on a background color

1

Galera, I have this code where it generates a kind of link theme and I'd like to apply that code to it for that the text contrasts with bg, How can I do this because my bg and the color of the text are random?

But I wanted the code to give me several contrast cores, not just one.

Code to leave text in contrast

var rgb = $('#content').css('backgroundColor');
var colors = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
var brightness = 1;

var r = colors[1];
var g = colors[2];
var b = colors[3];

var ir = Math.floor((255-r)*brightness);
var ig = Math.floor((255-g)*brightness);
var ib = Math.floor((255-b)*brightness);

$('#content').css('color', 'rgb('+ir+','+ig+','+ib+')');
    
asked by anonymous 22.07.2015 / 19:25

2 answers

2

Using a very good color rendering library called chroma.js you can easily manipulate background color gift and apply it in the color style of the text.

This is a function that returns the value of the background color by rgba

function GetBG(e) {
    var v = null;
    if (document.defaultView && document.defaultView.getComputedStyle) {
        var cs = document.defaultView.getComputedStyle(e, null);
        if (cs && cs.getPropertyValue) v = cs.getPropertyValue('background-color');
    }
    if (!v && e.currentStyle) v = e.currentStyle['backgroundColor'];
    return v;
};

With the background color data you can easily manipulate it:

function calculaBG(dom) {
    var $o = chroma(GetBG(dom));
    if ($o.luminance() < 0.5) return $o.brighten(2);
    else return $o.darken(2);
}

Function that calculates color, luminance ranges from 0 for black to 1 for white , in the above case if the luminance is less than 50% apply a lightening ( brighten ) relative to the background color, if it is greater than 50% it applies darken ( darken ) background color.

Follow the example in JSfiddle

    
22.07.2015 / 20:38
2

You can determine the distance of the colors to apply a different brightness according to the tolerance:

function isNeighborColor(color1, color2, tolerance) {
   // Função tirada da resposta:
   // https://stackoverflow.com/a/11506531/3497987
   // Se foi útil para você vá lá e de um voto a favor.
    if(tolerance == undefined) {
        tolerance = 32;
    }

    return Math.abs(color1.r - color2.r) <= tolerance
        && Math.abs(color1.g - color2.g) <= tolerance
        && Math.abs(color1.b - color2.b) <= tolerance;
}

var color = $('#test').css('backgroundColor');
var colors = color.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);

var rgb = {
    r: colors[1],
    g: colors[2],
    b: colors[3]
}

function GenerateRGB(rgb, brightness){
    var brightness = brightness == undefined ? 1 : brightness;
    var ir = Math.floor((255-rgb.r)*brightness);
    var ig = Math.floor((255-rgb.g)*brightness);
    var ib = Math.floor((255-rgb.b)*brightness);
    
    return {r: ir, g: ig, b: ib};
}

var nrgb = GenerateRGB(rgb, 1);
console.log(rgb, nrgb, isNeighborColor(rgb, nrgb, 165));

$('#test').css('color', 'rgb('+nrgb.r+','+nrgb.g+','+nrgb.b+')');

if (isNeighborColor(rgb, nrgb, 165))
    nrgb = GenerateRGB(rgb, 1.2);

$('#test2').css('color', 'rgb('+nrgb.r+','+nrgb.g+','+nrgb.b+')');
#test, #test2 {
 background-color: #422DAD;   
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><divid="test">Some text</div>
<br>
<div id="test2">Some other text</div>

Obsolete

As per this answer in English I gave the following example:

function CheckColor(c){
  // Código dessa função foi tirado da resposta
  // https://stackoverflow.com/a/12043228/3497987
    var c = c.replace('#', '');  // strip # 
    var rgb = parseInt(c, 16);   // convert rrggbb to decimal
    var r = (rgb >> 16) & 0xff;  // extract red
    var g = (rgb >>  8) & 0xff;  // extract green
    var b = (rgb >>  0) & 0xff;  // extract blue
    
    var luma = 0.2126 * r + 0.7152 * g + 0.0722 * b; // per ITU-R BT.709
    
  // Fiz alguns testes e identifique que o fator 160 é uma boa referência
  // Altere como desejar
  return (luma < 160);
}

// Função aleatorio e CorAleatoria
// foram usados códigos desse link
// http://www.criarweb.com/artigos/gerar-cor-aleatoria-javascript.html

function aleatorio(inferior,superior){ 
   numPossibilidades = superior - inferior;
   aleat = Math.random() * numPossibilidades;
   aleat = Math.floor(aleat);
   return parseInt(inferior) + aleat;
} 

function CorAleatoria(){ 
   hexadecimal = new Array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F");
   cor_aleatoria = "#";
   for (i=0;i<6;i++){ 
      posarray = aleatorio(0,hexadecimal.length);
      cor_aleatoria += hexadecimal[posarray];
   } 
   return cor_aleatoria ;
} 

// Conversão para Hexadecimal
// https://stackoverflow.com/a/1740716/3497987
var hexDigits = new Array
        ("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"); 

//Function to convert hex format to a rgb color
function rgb2hex(rgb) {
 rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
 return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

function hex(x) {
  return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
 }

// Aplica cor aleatória
var cor = CorAleatoria();
document.body.style.backgroundColor = cor;


// Verifica a cor de fundo e aplica cor da fonte
var corAleatoria = rgb2hex( document.body.style.backgroundColor );

document.body.style.color = CheckColor(corAleatoria) ? '#fff' : '#000' ;
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Debitis cupiditate adipisci reprehenderit ea iure laborum voluptate deserunt rerum ad placeat recusandae delectus nulla veritatis iste maxime ipsa odio sit vel.</p>

Run the code multiple times to test multiple colors.

    
22.07.2015 / 19:45