A TypeScript package to calculate WCAG 2.0/3.0 and APCA color contrasts

Overview

a11y-color-contrast

GitHub Actions Status npm

A simple utility package for working with WCAG 2.2/3.0 color contrasts

  • a11y: Built for checking how readable colors are together
  • Simple: Parsing of hex strings, contrast checks
  • WCAG: Support for checking both WCAG 2.0 and WCAG 3.0 contrasts
  • APCA: Support for the upcoming APCA contrast algorithm
Table of Contents

Installation

Deno

import { apcaContrastValue, hex, wcagContrastValue } from "https://deno.land/x/a11y_color_contrast/mod.ts";

const wcag = wcagContrastValue(hex("#e1e1e1"), hex("#fff"));
const apca = apcaContrastValue(hex("#e1e1e1"), hex("#fff"));

Node

Install the module with your favorite manager: npm add a11y-color-contrast

import { apcaContrastValue, hex, wcagContrastValue } from "a11y-color-contrast";

const wcag = wcagContrastValue(hex("#e1e1e1"), hex("#fff"));
const apca = apcaContrastValue(hex("#e1e1e1"), hex("#fff"));

Getting started

You can also read the documentation on Deno docs.

hex

hex is a utility function to parse a hex string to a [number, number, number], useful if your colors are not in the RBG format. Supports both short and long hex colors, and will strip out the alpha channel when the hex string contains it. Note, the returned tripled will contain NaN if the string cannot be parsed. Use isValidColor to check if the input can be invalid.

// import { hex } from "a11y-color-contrast";
import { hex } from "https://deno.land/x/a11y_color_contrast/mod.ts";

hex("#fff");
hex("#e1e1e1");

// Also support hex4/hex8
hex("#1234");
hex("#11ff0000");

// And missing #
hex("fff");

wcag

Based on the WCAG 2.2 algorithm to calculate how readable two colors are when used together. The first argument is the foreground color and the second the background. By default, the function defaults to checking whether the colors pass the WCAG AAA standard (7:1 contrast ratio) for normal text.

// import { hex, wcag } from "a11y-color-contrast";
import { hex, wcag } from "https://deno.land/x/a11y_color_contrast/mod.ts";

wcag(hex("#fff"), hex("#e1e1e1"));
// { level: "AAA", size: "normal", score: 1.3076906134240802, pass: false }

wcag(hex("#0f0f0f"), hex("#fff"));
// { level: "AAA", size: "normal", score: 19.168645448127652, pass: true }

wcag(hex("#0f0f0f"), hex("#f4f"), { level: "AA" });
// { level: "AA", size: "normal", score: 6.8668010864317885, pass: true }

wcag(hex("#0f0f0f"), hex("#f4f"), { level: "AA", size: "large" });
// { level: "AA", size: "large", score: 6.8668010864317885, pass: true }

wcagContrastValue

A simpler version of the wcag function, this returns the contrast value between two colors based on the WCAG 2.2 algorithm.

// import { hex, wcagContrastValue } from "a11y-color-contrast";
import { hex, wcagContrastValue } from "https://deno.land/x/a11y_color_contrast/mod.ts";

wcagContrastValue(hex("#fff"), hex("#e1e1e1"));
// 1.3076906134240802

wcagContrastValue(hex("#0f0f0f"), hex("#fff"));
// 19.168645448127652

wcagIsReadable

A simpler version of the wcag function, this checks whether two colors used together are readable based on the WCAG parameters passed.

// import { hex, wcagIsReadable } from "a11y-color-contrast";
import { hex, wcagIsReadable } from "https://deno.land/x/a11y_color_contrast/mod.ts";

wcagIsReadable(hex("#fff"), hex("#e1e1e1"));
// false

wcagIsReadable(hex("#0f0f0f"), hex("#fff"));
// true

wcagIsReadable(hex("#0f0f0f"), hex("#f4f"), { level: "AAA" });
// false

wcagIsReadable(hex("#0f0f0f"), hex("#f4f"), { level: "AA" });
// true

apcaContrastValue

Based on the upcoming WCAG 3.0 standard, this function is based on the APCA algorithm to calculate how readable two colors are when used together. The first argument is the foreground color and the second the background. It is highly recommended reading the linked article and resources to get an overview over the differences between the WCAG and APCA standard.

// import { apcaContrastValue, hex } from "a11y-color-contrast";
import { apcaContrastValue, hex } from "https://deno.land/x/a11y_color_contrast/mod.ts";

apcaContrastValue(hex("#fff"), hex("#e1e1e1"));
// -17.5

apcaContrastValue(hex("#0f0f0f"), hex("#fff"));
// 105.5

apcaContrastValue(hex("#0f0f0f"), hex("#f4f"));
// 51.2

apcaToInterpolatedFont

Based on a Lc between two colors, this will find the appropriate font sizes for it. The returned array will show "placeholder" for when the contrast is too low for text and "prohibited" when the contrast is unusable and otherwise a font size. If no font size can be calculated it will return null.

The returned array contains nine values, corresponding to the font useable at font weight 100 at index 0, and so on until weight 900 at index 8.

// import { apcaToInterpolatedFont, hex } from "a11y-color-contrast";
import { apcaToInterpolatedFont, hex } from "https://deno.land/x/a11y_color_contrast/mod.ts";

apcaToInterpolatedFont(-17.5);
//  100 200 300 400 500 600 700 800 900
// [ "placeholder", ...]

apcaToInterpolatedFont(105.5);
//  100  200 300 400   500 600 700 800 900
// [ 39, 25, 18, 14.5, 14, 13, 12, 16, 18 ]

apcaToInterpolatedFont(51.2);
//  100  200 300 400 500 600   700   800   900
// [ 92, 69, 57, 31, 27, 23.5, 20.5, 20.5, 20.5 ]

apcaValidateFont

Based on a Lc value, this function allows you to check whether a given font and weight combination passes the required minimum contrast based on the APCA contrast table.

The first parameter is the Lc value, the second is either a single font size or an array of them and the third, optional parameter is either a single font weight or an array of them. If the weight parameter is undefined, it will default to all the font weights.

// import { apcaValidateFont, hex } from "a11y-color-contrast";
import { apcaValidateFont, hex } from "https://deno.land/x/a11y_color_contrast/mod.ts";

apcaValidateFont(-17.5, 36, 800);
// { "36": { "800": false } }

apcaValidateFont(105.5, [14, 16, 18], [400, 600, 800]);
// {
//   "14": { "400": true, "600": true, "800": false },
//   "16": { "400": true, "600": true, "800": true },
//   "18": { "400": true, "600": true, "800": true }
// }

apcaValidateFont(51.2, [18, 32]);
// {
//   "18": { "100": false, "200": false, ..., "700": false, "800": false, "900": false },
//   "32": { "100": false, "200": false, ..., "500": true, "600": true, "700": true, "800": true, "900": true }
// }

Utility functions

toHex

Converts an RGB triplet to its hex string representation.

// import { toHex } from "a11y-color-contrast";
import { toHex } from "https://deno.land/x/a11y_color_contrast/mod.ts";

toHex([0, 0, 0]);
// "#000000"

isValidColor

Checks whether a color parsed via hex is valid.

// import { isValidColor } from "a11y-color-contrast";
import { isValidColor } from "https://deno.land/x/a11y_color_contrast/mod.ts";

isValidColor([0, 0, 0]);
// true

isValidColor([NaN, 0, 0]);
// false

colorFromObject

Converts an RGB object into an RGB triplet.

// import { colorFromObject } from "a11y-color-contrast";
import { colorFromObject } from "https://deno.land/x/a11y_color_contrast/mod.ts";

colorFromObject({ r: 0, g: 0, b: 0 });
// [0, 0, 0]

Inspiration and resources

License

MIT

You might also like...

A simple color picker application written in pure JavaScript, for modern browsers.

A simple color picker application written in pure JavaScript, for modern browsers.

Color Picker A simple color picker application written in pure JavaScript, for modern browsers. Has support for touch events. Touchy… touchy… Demo and

Dec 14, 2022

A dependency-free image color extraction library

A dependency-free image color extraction library

Color mage A dependency-free image color extraction library. The extraction consists of using K-Means algorithm. It has a few utility functions as wel

Mar 11, 2022

A array with color name - decimal rgbs.

colors-named-decimal A array with color name - decimal rgbs. Based on https://www.w3.org/TR/css-color-4/#colors-named Installation This package is ES

Jul 20, 2022

This repo contains resources & practice of project and files , while learning to master JS

Resources to learn JavaScript and conquer the world? Tutorials and Books JavaScript For Cats (http://jsforcats.com/) is a dead simply introduction for

Jan 6, 2022

Tints and shades generator in React.

Tints and shades generator in React.

Reactry's shades goals add option to enter hexColor by hand add option to get hexColor from clipboard add option to set one of the shades or tints as

May 26, 2022

A CLI utility to calculate/verify accessible magic numbers for a color palette.

A CLI utility to calculate/verify accessible magic numbers for a color palette.

A11y Contrast A CLI utility to calculate/verify accessible magic numbers for a color palette. Read my blog post for some more information. Installatio

Nov 13, 2022

A WCAG-conformant (2.1 AA) Ember starter app.

accessibility-base Some small changes to make to your new Ember app to make it WCAG conformant: adds lang attribute in app/index.html (you can also do

May 17, 2022

A NodeJS package to convert any RGB color to HEX color or viceversa. Also supports HSL conversion.

Unhex 🎨 A NodeJS package to convert any RGB color to HEX, HSL color or viceversa. Example div { color: #fff; background-color: #0070f3; } After r

Oct 1, 2022

Colormath.js - a color conversion and color manipulation library written in typescript for Node.js, Deno and Browser

Colormath.js - a color conversion and color manipulation library written in typescript for Node.js, Deno and Browser

Feb 8, 2022

Tool Cool Color Picker is a color picker library written in typescript and using web component technologies.

Tool Cool Color Picker is a color picker library written in typescript and using web component technologies.

Tool Cool Color Picker Tool Cool Color Picker is a color picker library written in typescript and using web component technologies. Check out the demo

Oct 23, 2022

Convert and Calculate by RPN for typescript.

Coaca.ts: Convert and Calculate by RPN for typescript 注意点 まずそもそも、typescriptはサーバサイドで使用されるべき言語です。一応typescript4.5以降の機能を用いていますが、typescriptの本来の使い方を超越してます。ご

Aug 24, 2022

🦎 A jQuery plugin for extracting the dominant color from images and applying the color to their parent.

🦎 A jQuery plugin for extracting the dominant color from images and applying the color to their parent.

jquery.adaptive-backgrounds.js A simple jQuery plugin to extract the dominant color of an image and apply it to the background of its parent element.

Dec 21, 2022

Change the color of an image to a specific color you have in mind.

image-recolor Run it: https://image-recolor.vercel.app/ image.recolor.mov Acknowledgments Daniel Büchele for the algorithm: https://twitter.com/daniel

Oct 25, 2022

A little toy app to help you find the nearest match for a given color within a Figma Tokens color palette.

A little toy app to help you find the nearest match for a given color within a Figma Tokens color palette.

Hey Palette So you've got a color palette in Figma and you've used the Figma Tokens plugin to export that palette to JSON. Let's say you have a color

Nov 15, 2022

Colr Pickr, a vanilla JavaScript color picker component built with SVGs, with features like saving colors. Similar design to the chrome-dev-tools color picker.

Colr Pickr, a vanilla JavaScript color picker component built with SVGs, with features like saving colors. Similar design to the chrome-dev-tools color picker.

Colr Pickr Colr Pickr, a vanilla JavaScript color picking component built with SVGs, with features like saving colors. Similar design to the chrome-de

Jun 27, 2022

Chart.js plugin to calculate and draw statistical linear, exponential, power, logarithmic, and polynomial regressions.

chartjs-plugin-regression Chart.js plugin to calculate and draw statistical linear, exponential, power, logarithmic, and polynomial regressions using

Dec 18, 2022

A concise collection of classes for PHP, Python, JavaScript and Ruby to calculate great circle distance, bearing, and destination from geographic coordinates

GreatCircle A set of three functions, useful in geographical calculations of different sorts. Available for PHP, Python, Javascript and Ruby. Live dem

Sep 30, 2022

Package fetcher is a bot messenger which gather npm packages by uploading either a json file (package.json) or a picture representing package.json. To continue...

package-fetcher Ce projet contient un boilerplate pour un bot messenger et l'executable Windows ngrok qui va permettre de créer un tunnel https pour c

Mar 29, 2022

Calculate the price range for property advertised on Domain and Real Estate.

Calculate the price range for property advertised on Domain and Real Estate.

Property Seeker Calculate the price range for property advertised on Domain and Real Estate. Install Chrome Firefox Edge Privacy All searches are perf

Dec 27, 2022
Releases(v0.2.0)
  • v0.2.0(Jul 19, 2022)

    v0.2.0

    2022-07-19

    Summary

    Fixed some unfortunate misspellings of WCAG, renamed a bunch of functions and added lots more documentation.

    Commits

    • [2d95d74] Yet another tiny mistake
    • [105b82b] Temporarily disable doc tests
    • [a5f5ea9] Update README
    • [145b249] Fix totally wrong values in apcaContrastValue docs
    • [ad05e86] Add documentation to isValidColor
    • [12eb2e9] Rename more things, more documentation
    • [a0eebf0] Create new wcagContrastValue function, more documentation
    • [170b205] Yeah, nah, no more grouped exports
    • [99d110c] And export the class
    • [0027b63] Fix names being wrong :facepalm:
    • [bdb7b48] Try with a class instead
    • [75818aa] Actually export wcag object
    • [797f2a1] Function renaming, add documentation
    • [cfc5893] Convert functions to named functions for deno doc
    • [e9b3e07] Add documentation, example to 'toHex' function
    • [0d20fe6] Change toHex method to use bit shifting dark magics
    • [cfb3d73] Run doctests on CI, fix README/examples so they compile
    • [f53d244] Fix wrong URL to documentation

    v0.1.0

    2022-07-19

    Summary

    Initial release of the package. See the README for usage notes.

    Commits

    • [e8bfaf1] Move node setup to top of pipeline
    • [b46fd9a] Publish job depends on the pipeline job
    • [f27a99d] Make publish step a separate CI job
    • [b11d19d] Run dnt on CI, add publishing step and tasks
    • [5b25f03] Fix links in README
    • [1eaaefe] Fix number 100 for optional, partial, default options
    • [8023a6f] Update README
    • [84c3904] Remove uneeded function, fix passing WCAG parameters
    • [590de6c] Remove redundant assert in tests
    • [633ea4c] Create utility function to validate a font against a Lc value
    • [6cb7616] Add documentation
    • [97c6609] Refactor and simplify some APCA functions
    • [19c1267] Add tests to the interpolated font lookup
    • [9258c5a] Implement fontLookupAPCA
    • [35602d8] Add contrast to font size table
    • [12b3e0a] Add function to get font size contrast
    • [e2de2a6] Refactor font contrast to a record object
    • [9fd2cd2] Add APCA font to contrast table
    • [c061efe] Rename generic 'Readability' type to 'WCAG'
    • [7cc8203] Fix some exporting names
    • [ce84c99] Fix formatting, convert deno.json -> deno.jsonc
    • [fd7ca69] Add dnt build tool for npm publishing
    • [3105938] Update README
    • [8bb9e82] Hide internal parsing functions
    • [1f9a9d3] Change Color type to be a tuple instead of object
    • [0755453] Remove WCAG 2.0/2.1 stuff
    • [4a52171] Add APCA contrast checking from WCAG3.0
    • [6328844] Add WCAG 2.0/2.1/2.2 changes to code
    • [755ea00] Extract WCAG stuff to their own file
    • [7be066b] Fix stupid misspelling of RGB
    • [ad5d21d] Start extracting functionality into small functions
    • [318ffd0] Extract parsing to its own file
    • [30108be] Port over color code from empyreum
    • [f877b41] Add basic RGB and RGBA functionality
    Source code(tar.gz)
    Source code(zip)
  • v0.1.0(Jul 19, 2022)

    v0.1.0

    2022-07-19

    Summary

    Initial release of the package. See the README for usage notes.

    Commits

    • [e8bfaf1] Move node setup to top of pipeline
    • [b46fd9a] Publish job depends on the pipeline job
    • [f27a99d] Make publish step a separate CI job
    • [b11d19d] Run dnt on CI, add publishing step and tasks
    • [5b25f03] Fix links in README
    • [1eaaefe] Fix number 100 for optional, partial, default options
    • [8023a6f] Update README
    • [84c3904] Remove uneeded function, fix passing WCAG parameters
    • [590de6c] Remove redundant assert in tests
    • [633ea4c] Create utility function to validate a font against a Lc value
    • [6cb7616] Add documentation
    • [97c6609] Refactor and simplify some APCA functions
    • [19c1267] Add tests to the interpolated font lookup
    • [9258c5a] Implement fontLookupAPCA
    • [35602d8] Add contrast to font size table
    • [12b3e0a] Add function to get font size contrast
    • [e2de2a6] Refactor font contrast to a record object
    • [9fd2cd2] Add APCA font to contrast table
    • [c061efe] Rename generic 'Readability' type to 'WCAG'
    • [7cc8203] Fix some exporting names
    • [ce84c99] Fix formatting, convert deno.json -> deno.jsonc
    • [fd7ca69] Add dnt build tool for npm publishing
    • [3105938] Update README
    • [8bb9e82] Hide internal parsing functions
    • [1f9a9d3] Change Color type to be a tuple instead of object
    • [0755453] Remove WCAG 2.0/2.1 stuff
    • [4a52171] Add APCA contrast checking from WCAG3.0
    • [6328844] Add WCAG 2.0/2.1/2.2 changes to code
    • [755ea00] Extract WCAG stuff to their own file
    • [7be066b] Fix stupid misspelling of RGB
    • [ad5d21d] Start extracting functionality into small functions
    • [318ffd0] Extract parsing to its own file
    • [30108be] Port over color code from empyreum
    • [f877b41] Add basic RGB and RGBA functionality
    Source code(tar.gz)
    Source code(zip)
Owner
Sondre Aasemoen
Rust | Kotlin | TypeScript | React.
Sondre Aasemoen
Colormath.js - a color conversion and color manipulation library written in typescript for Node.js, Deno and Browser

Colormath.js - a color conversion and color manipulation library written in typescript for Node.js, Deno and Browser

TheSudarsanDev 8 Feb 8, 2022
A tool for creating and maintaining cohesive, consistent, and accessible color palettes

Primer Prism Primer Prism is a tool for creating and maintaining cohesive, consistent, and accessible color palettes. ?? primer.style/prism ?? Read th

Primer 517 Jan 3, 2023
A simple Discord bot that will listen for HEX, RGB(a), and HSL(a) colors in a message, and provide a small image of that color.

Pigment For the teams of designers and developers out there - Pigment will listen for messages containing a HEX, RGB(a), or HSL(a) color, and provide

Conrad Crawford 17 Dec 8, 2022
:rainbow: Javascript color conversion and manipulation library

color JavaScript library for immutable color conversion and manipulation with support for CSS color strings. var color = Color('#7743CE').alpha(0.5).l

Qix 4.5k Jan 3, 2023
JavaScript Library for creating random pleasing colors and color schemes

#PleaseJS www.checkman.io/please Please.js is a polite companion that wants to help you make your projects beautiful. It uses HSV color space to creat

Jordan Checkman 2.3k Dec 22, 2022
Fast, small color manipulation and conversion for JavaScript

TinyColor JavaScript color tooling TinyColor is a small, fast library for color manipulation and conversion in JavaScript. It allows many forms of inp

Brian Grinstead 4.5k Jan 1, 2023
Coloris - A lightweight and elegant JavaScript color picker. Written in vanilla ES6, no dependencies. Accessible.

Coloris A lightweight and elegant JavaScript color picker written in vanilla ES6. Convert any text input field into a color field. View demo Features

Momo Bassit 126 Dec 27, 2022
Color2k - a color parsing and manipulation lib served in roughly 2kB

color2k a color parsing and manipulation lib served in roughly 2kB or less (2.8kB to be more precise) color2k is a color parsing and manipulation libr

Rico Kahler 506 Dec 31, 2022
Create your own complete Web color system fast and easy!

Simpler Color Create your own complete Web color system fast and easy, from as little as one base color! Color is at the heart of every UI design syst

Arnel Enero 278 Dec 20, 2022
JavaScript library for all kinds of color manipulations

Chroma.js Chroma.js is a tiny small-ish zero-dependency JavaScript library (13.5kB) for all kinds of color conversions and color scales. Usage Initiat

Gregor Aisch 9.2k Jan 4, 2023