Skip to content

Instantly share code, notes, and snippets.

@davelandry
Last active August 22, 2016 15:24
Show Gist options
  • Save davelandry/b3063df74711f4e69166 to your computer and use it in GitHub Desktop.
Save davelandry/b3063df74711f4e69166 to your computer and use it in GitHub Desktop.
Make Colored Text Legible on White Backgrounds

Using d3plus.color.legible, a color's luminosity and saturation can be tweaked so that it is much easier to read on a white background, while still retaining as much of the original color as possible.

This example shows how various colors are modified using this function. The lighter colors are darkened the most.

Featured on D3plus.org

<!DOCTYPE html>
<meta charset="utf-8">
<script src="//d3plus.org/js/d3.js"></script>
<script src="//d3plus.org/js/d3plus.js"></script>
<style>
div#grid {
margin: 25px auto;
text-align: center;
width: 700px;
}
div.color {
border-left: 25px solid;
display: inline-block;
margin: 10px;
padding: 0px 10px;
width: 50px;
}
div.text {
font: 11px "Helvetica", "Arial", sans-serif;
margin: 5px 0px;
}
</style>
<div id="grid"></div>
<script>
var colors = d3plus.color.scale.range()
colors = colors.concat(["#525252", "#737373", "#969696", "#bdbdbd", "#d9d9d9", "#f7f7f7"])
var squares = d3.select("#grid").selectAll("div.color")
.data( colors )
.enter().append("div")
.attr("class","color")
.attr("id", String)
.style("border-color", String)
squares.selectAll(".text")
.data([ "Original" , "Legible" ])
.enter().append("div")
.attr("class","text")
.style("color", function(d) {
var color = this.parentNode.id
return d === "Legible" ? d3plus.color.legible(color) : color
})
.text(String)
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment