A set of methods for working with contrasting colors.
Use cases:
- Get contrasting text color for a given background
- Pick color from the list that has most contrast with a target color
- Get color relative luminance
- Get contrast difference between two colors
- Get contrast ratio between two colors
- Check if two colors have sufficient contrast difference
TypeScript Docs: https://n1kk.github.io/counter-color/
Demo page: https://n1kk.github.io/counter-color/demo.html
Install:
# npm
npm i counter-color
# yarn
yarn add counter-color
# pnpm
pnpm i counter-color
Get a most contrasting color for a given one. Defaults are black and white.
targetColor
: supported color valueoptions
: optional object that allows you to configure:light
color: stringdark
color: string- luminosity
threshold
: number (0-1)
- returns:
string
of a color which has most contrast with the given background
import counterColor from "counter-color";
const textColor1 = counterColor("#00F"); // "#000000"
const textColor2 = counterColor("#0F0"); // "#FFFFFF"
const options = { dark: "#222", light: "#eee", threshold: 0.4 };
const textColor3 = counterColor("#f00", options); // "#eee"
- A supported color value:
- int:
0 - 16777215
, - rgb array of int (0-255):
[255, 0, 0]
, - hex color in web or full format:
#RGB
|#RRGGBB
|#RRGGBBAA
- int:
Calculates contrast difference of two colors.
color1
,color2
: supported color value- returns:
number
0-1- 0: no difference
- 1: max contrast, black and white
const bnw = colorsContrast("#000", "#FFF"); // 1
const sameColor = colorsContrast("#000", "#000"); // 0
Calculates color contrast ratio based on W3C spec
color1
,color2
: supported color value- returns:
number
between 1 (1:1 ratio) and 0.476... (1:21 ratio),- 1:1 : no contrast, same color
- 1:21 : max contrast, black and white
const bnw = colorsContrastRatio("#000", "#FFF"); // 1/21 (0.047..)
const sameColor = colorsContrastRatio("#000", "#000"); // 1
Check if colors have suffiecient contrast ratio (7:1) as defined by W3C spec
color1
,color2
: supported color value- returns:
boolean
colorsHaveSufficientContrast("#000", "#FFF"); // true
colorsHaveSufficientContrast("#000", "#000"); // false
Pick a color from the list that has the most contrast with the target.
color
: an array of supported color values- returns: value from the list
pickMostContrast(["#fff", "#f00", "#00f", "#000"], "#000"); // "#fff"
pickMostContrast(["#fff", "#f00", "#00f", "#000"], "#fff"); // "#000"
Calculates relative color luminance as per W3C spec
color
: supported color value- returns:
number
0-1
colorLuminance("#fff"); // 1
colorLuminance("#000"); // 0
colorLuminance("#F00"); // 0.21...
Convert a hex color #RGB
| #RRGGBB
to rgb array.
Convert an integer color to rgb array.
Convert a color values to rgb array. Throws on invalid input.
Convert a rgb array to a hex color string.
Convert an integer to a hex color string.
Convert a hex color string to an integer.
Convert a rgb array to an integer.