Reputation: 43843
In javascript/jquery, if I have two colors in HSL (or hex or rgb) format, is there an algorithm that can check if the contrast is bad? One color is text, and the other color is the background of the text. I need to follow standard accessibility guidelines and make sure the text is well readable. So I think I need to check if the contrast is good enough between the two values.
Thanks
Upvotes: 0
Views: 1654
Reputation: 104780
This example returns an array with the relative brightness and color contrast of two colors (passed in as rgb strings or 3-member arrays).
The formula is from : http://www.w3.org/TR/AERT#color-contrast.
Deciding what values are contrasty enough is subjective, the W3 article suggests [125,500] as minimums.
function contrast(F, B){
F= String(F).match(/\d+/g),
B= String(B).match(/\d+/g);
var abs= Math.abs,
BG= (B[0]*299 + B[1]*587 + B[2]*114)/1000,
FG= (F[0]*299 + F[1]*587 + F[2]*114)/1000,
bright= Math.round(Math.abs(BG - FG)),
diff= abs(B[0]-F[0])+abs(B[1]-F[1])+abs(B[2]-F[2]);
return [bright, diff];
}
var f= 'rgb(255,255,255)', b= 'rgb(255,0,0)';
contrast(f,b)>>> returned value: (Array)[179,510]
Upvotes: 1