font-color-contrast

JavaScript module to select black or white to a font according to the background for the best possible contrast.
Calculates the best color (black or white) to contrast with the passed color using the algorithm from https://alienryderflex.com/hsp.html
Installation
$ npm i font-color-contrast
Usage
You can use the module 4 ways, with an optional parameter (from 0 to 1) for contrast threshold:
- with a hexadecimal color string
- fontColor('#f7d4fc')
- fontColor('f7d4fc')
- fontColor('f7d4fc', 0.2)
- with a color number
- fontColor(0xf7d56a)
- fontColor(16242026)
- fontColor(16242026, 0.8)
- with an array of numbers with the RGB color:
- fontColor([223, 0, 255])
- fontColor([0xf7, 0, 0xff])
- fontColor([0xf7, 0, 0xff], 0.4)
- with the RGB color numbers:
- fontColor(223, 0, 255)
- fontColor(0xf7, 0, 0xff)
- fontColor(0xf7, 0, 0xff, 0.4)
Example:
import fontColorContrast from 'font-color-contrast'
const myStringBg = '#00CC99'
const fontColor = fontColorContrast(myStringBg)
const myNumberBg = 0x00cc99
const fontColor = fontColorContrast(myNumberBg)
const red = 0
const green = 204
const blue = 153
const fontColor = fontColorContrast(red, green, blue)
const myArrayBg = [0, green: 204, blue: 153]
const fontColor = fontColorContrast(myArrayBg)
Optionally, you can pass the contrast threshold (defaults to 0.5). This will affect the resulting font color. The use of this parameter is to control the WCAG conformance levels.
import fontColorContrast from 'font-color-contrast'
fontColorContrast('#645466', 0)
fontColorContrast('#645466', 1)
The 4 possible overflows are described next:
function fontColorContrast (hex: number, threshold?: number): '#ffffff' | '#000000'
function fontColorContrast (hex: string, threshold?: number): '#ffffff' | '#000000'
function fontColorContrast (red: number, green: number, blue: number, threshold?: number): '#ffffff' | '#000000'
function fontColorContrast(redGreenBlue: number[], threshold?: number): '#ffffff' | '#000000'
Tests
Tests made using Jest to check color format possibilities and contrast, including all CSS colors and WebSafe (90's stuff) colors as shown in the image below
Examples
These examples are using the default 0.5 threshold.
WebSafe colors

CSS colors

Version history
0 -> 8.1.1
JavaScript version, accepting strings for RGB
9.0.0 -> 9.0.2
TypeScript version.
Only numbers are now accepted as params when using array or RGB, because it was impossible to know if the string was decimal or hexadecimal. Accepting only numbers we can be sure the correct values are being used to calculate the contrast.
9.1.0
Updated algorithm from https://alienryderflex.com/hsp.html with new thresholds for better contrast.
10.0.0
Included the optional threshold parameter (thanks, franciscohanna92).
10.0.1
Changed target to ES2015