Invert Color for "Button"

creating a button using a canvas… each button will have a background color (it could be anything).
SOME of the buttons may have a bit of text in them as well…
The problem is how to figure out what the best color for the text would be so it doesn’t get lost in the background

Note : The background color is NOT static, as a matter of fact it is used to the result for a color picker, so the text color needs to transform as the background color is changed. The text color can be just black or white, but how to decide when black is more readable than white for a particular background color?

Google’d “how to decide when black is more readable than white for a particular background color”
Found this: http://stackoverflow.com/a/3943023

yeah… I found that a few minutes later myself…

if (red*0.299 + green*0.587 + blue*0.114) > 186 use #000000 else use #ffffff

works pretty well… but I think 150 instead of 186 might be better for what I’m doing