As others have noted in their comments / answers, the difference between the two colors will be important.
W3 has already created a method that determines the minimum contrast between colors to convey levels of accessibility.
They provide a description here , and the formula for the calculation is on the same page below here :
contrast ratio = (L1 + 0.05) / (L2 + 0.05)
For this apparently simple formula, you will need to calculate the relative brightness marked by L1 and L2 both colors using a different formula, which you will find here :
L = 0.2126 * R + 0.7152 * G + 0.0722 * B where R, G and B are defined as: if RsRGB <= 0.03928 then R = RsRGB/12.92 else R = ((RsRGB+0.055)/1.055) ^ 2.4 if GsRGB <= 0.03928 then G = GsRGB/12.92 else G = ((GsRGB+0.055)/1.055) ^ 2.4 if BsRGB <= 0.03928 then B = BsRGB/12.92 else B = ((BsRGB+0.055)/1.055) ^ 2.4
and RsRGB, GsRGB and BsRGB are defined as:
RsRGB = R8bit/255 GsRGB = G8bit/255 BsRGB = B8bit/255
The minimum contrast ratio between text and background should be 4.5: 1 for AA and 7: 1 for AAA. This still leaves room for good designs.
There is an example implementation in JS from Lea Verou .
This will not give you the closest color as you requested, because on a unique background there will be more than one frontal color giving the same contrast result, but this is the standard way to calculate contrasts.
Zimmi source share