Horay Horay - 3 months ago 19
Javascript Question

Dynamically change color based on brightness of background color

I'm using color.js to convert and do things with colors. I have a few elements which I want to dynamically change based on the background color. So if the background color is dark, then make the text white. If it's light then make the text black.

That is simple to do:

myElem.color = color.RGBLuminance > 0.22 ? 'black' : 'white';


But I will also have alpha. How can I test against alpha and the brightness of the background?

JSFiddle





var myColor = new Colors();

var div = document.getElementById('div'),
span = document.getElementById('span'),
rgbColor = myColor.colors.RND.rgb;

myColor.setColor({
r: 0,
g: 0,
b: 0
}, 'rgb');
/*myColor.setColor({
r: 100,
g: 200,
b: 255
}, 'rgb');*/

div.style.backgroundColor = rgba(rgbColor.r, rgbColor.g, rgbColor.b, 0.3);

span.style.color = myColor.colors.RGBLuminance > 0.22 ? 'black' : 'white';



function rgba(r, g, b, a) {
return "rgba(" + r + "," + g + "," + b + "," + a + ")";
}

#div {
width: 200px;
height: 200px;
}

<div id="div">
<span id="span">hello</span>
</div>
<script src="https://rawgit.com/PitPik/colorPicker/master/colors.js"></script>




Answer

You can retrieve the alpha value for your color with

myColor.colors.alpha

So you can use a check similar to:

span.style.color = myColor.colors.RGBLuminance > 0.22 || myColor.colors.alpha < 0.5 ? 'black' : 'white';

You'll likely have to play around with the conditions (or add more cases) to get the behavior you want.

Comments