Last active
July 7, 2016 05:07
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Run it