Calculate and Improve Color Contrast To Enhance Accessibility – a11y-contrast-color

Category: Color , Javascript | August 19, 2024
Authormoong23
Last UpdateAugust 19, 2024
License
Views43 views
Calculate and Improve Color Contrast To Enhance Accessibility – a11y-contrast-color

The a11y-contrast-color library helps web developers create accessible color schemes.

It calculates luminance and contrast ratios to ensure that text remains readable against various backgrounds.

In addition, the library provides a utility to recommend suitable contrast colors to maintain WCAG compliance.

How to use it:

1. Install the a11y-contrast-color library using your preferred package manager:

# Yarn
$ yarn add a11y-contrast-color
# NPM
$ npm install a11y-contrast-color

2. Determine the luminance of a given color using the ‘getLuminance()’ function. You pass an array containing the RGB values (ranging from 0 to 255) of the color, and it returns the calculated luminance value.

import { getLuminance } from 'a11y-contrast-color';
const luminance = getLuminance([255, 255, 0]);
// => 0.9278
console.log(luminance);

3. Calculate the contrast ratio between two colors using the ‘getContrastRatio()’ function. . Provide the RGB values of both colors, and the function returns the calculated contrast ratio.

import { getContrastRatio } from 'a11y-contrast-color';
const color1 = [255, 0, 0];
const color2 = [255, 255, 0];
const contrastRatio = getContrastRatio(color1, color2);
// => 3.7235338918507237
console.log(contrastRatio);

4. Suggest an appropriate contrast color (black or white) for a given background color to guarantee readability. Input the background color’s RGB values and the desired target luminance ratio. The function returns the RGB values of the suggested contrast color. If no suitable color is found, it returns null.

import { getContrastColor } from 'a11y-contrast-color';
const contrastColor = getContrastColor([0, 0, 0], 5);
// => [132, 191, 119]
console.log(contrastColor);

Changelog:

08/19/2024

  • v1.1.0

You Might Be Interested In:


Leave a Reply