Skip to content

Commit 0282a21

Browse files
author
Chris K
committed
Added getLuminance and getContrastRatio in Colors.
1 parent d6b6945 commit 0282a21

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

src/scripts/colors.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -505,6 +505,30 @@ Color.prototype = new function()
505505
return this.rgb_to_hex_c(this.__rgb).toUpperCase();
506506
}
507507

508+
// http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef
509+
this.getLuminance = function()
510+
{
511+
var RGB = this.__rgb.map(function(c)
512+
{
513+
var cs = c / 255;
514+
return cs <= 0.03928
515+
? cs / 12.92
516+
: Math.pow(((cs + 0.055) / 1.055), 2.4);
517+
});
518+
return 0.2126 * RGB[0] + 0.7152 * RGB[1] + 0.0722 * RGB[2];
519+
};
520+
521+
// http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef
522+
this.getContrastRatio = function(color2)
523+
{
524+
var l1 = this.getLuminance();
525+
var l2 = color2.getLuminance();
526+
return l1 > l2
527+
? (l1 + 0.05) / (l2 + 0.05)
528+
: (l2 + 0.05) / (l1 + 0.05);
529+
};
530+
531+
508532
this._alpha2string = function()
509533
{
510534
if (typeof this.alpha == 'number')

0 commit comments

Comments
 (0)