Skip to content

Instantly share code, notes, and snippets.

@hssm
Last active July 7, 2016 05:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hssm/0d63eb83541d85793bc0d6c74b724a05 to your computer and use it in GitHub Desktop.
Save hssm/0d63eb83541d85793bc0d6c74b724a05 to your computer and use it in GitHub Desktop.
An early attempt at deciding on a text color to ensure visibility using some approaches I found on SO. It doesn't work very well.
<html>
<head>
<meta charset="utf-8">
<style>
.box {
width: 80px;
height: 80px;
padding: 5px;
line-height: 2em;
text-align: center;
font-size: 18px;
font-weight: 700;
margin: 5px;
float: left;
}
</style>
<script>
function componentToHex(c) {
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
};
function setColorByLuma(box) {
if (getComputedStyle(box).backgroundColor == 'transparent') {
// Firefox doing some weird stuff. Skip over it.
box.style.display = "none";
return;
}
// Get RGB value and split it into the 3 components
var comp = getComputedStyle(box).backgroundColor.split("(")[1].split(")")[0].split(", ");
var c = componentToHex(comp[0]) + componentToHex(comp[1]) + componentToHex(comp[2]); // hex color value
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
//var luma = (r + g + b) / 3;
box.innerHTML = (""+luma).substring(0, 5) + "<div>▶</div>";
if (luma < 65) {
box.style.color = "#fff";
} else {
box.style.color = "#000";
}
console.log("Computed: " + getComputedStyle(box).backgroundColor);
console.log("RGB: " + rgb);
console.log("HEX:" + c);
console.log("LUMA: " + luma);
};
window.onload = function () {
// First two boxes can be pure white and black
d = document.createElement('div');
d.className = "box";
d.style.backgroundColor = "#fff";
document.body.appendChild(d);
setColorByLuma(d);
d = document.createElement('div');
d.className = "box";
d.style.backgroundColor = "#000";
document.body.appendChild(d);
setColorByLuma(d);
/*Create random boxes for testing*/
for (i=0; i < 1000; i++) {
d = document.createElement('div');
d.className = "box";
d.style.backgroundColor = ('00000'+(Math.random()*(1<<24)|0).toString(16)).slice(-6);
document.body.appendChild(d);
setColorByLuma(d);
}
};
</script>
</head>
<body>
</body>
</html>
@hssm
Copy link
Author

hssm commented Jul 6, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment