Skip to content

Instantly share code, notes, and snippets.

@hssm hssm/visibility_test.html
Last active Jul 7, 2016

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

hssm commented Jul 6, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.