How can I choose a legible color to draw text on a bar in a d3js chart?

683 views Asked by At

I have a bar chart done using d3 and I would like to put text on the bars. How can I choose the most legible color for the text e.g. white for dark bars and black for others? I can't choose the bar colors but I do know what color each bar is when I append the text.

PS: The possible duplicate is a general Javascript solution, its much easier with d3.

1

There are 1 answers

0
David Tinker On

The d3 specific solution to this is simple:

var color = .. function giving color of the bar ..
text.style("fill", function(d) { return d3.hsl(color(d)).l > 0.5 ? "#000" : "#fff" })

Thanks @Jamiec for the link.