Calculating a text color based off of a background (not just black or white)

367 Views Asked by At

I'm currently trying to build a feature in typescript that automatically generates a text color that works on top of a background that follows the AA WCAG 2 or APCA standards. The problem is that I can can find lots of examples that show this by changing the text to either white or black. The issue is that I want to actually still preserve the color in the text. For example on the coolors.co site:

coolors.co palette generator

I've tried using HSL and modifying the lightness value, but I still have issue getting it reliably generating good text colors. Any help or leads on this would be much appreciated!

Here's what I'm trying to use it for:

anime card with auto generated text colors

1

There are 1 best solutions below

0
Myndex On

Short Answer

Munawwar Firoz built a tool that does this, the GitHub repo.

Longer Answer

In the apca-w3 package (on npm, and GitHub), there is reverseAPCA(Lc,Ys,'bg','Y') which takes the contrast and the estimated screen luminance. In this example, Ys from the BG, and then returns a grayscale value, or a Ys value, to match the desired contrast.

From the Ys value you can re-add hue, and some amount of saturation or chroma, using HSLuv.

Process

  1. Determine the hue and saturation of the starting color, or the intended target color.

  2. Calculate the Ys of the known color. For example, our BG is 0.85 Ys

  3. Send the target desired Lc contrast value to reverseAPCA() along with the knownYs from the previous step, the color (bg or txt) that Ys represents, and the desired return type ('hex','color','Y').


  let textYs = reverseAPCA(60,0.85,'bg','Y');

// expected: textYs is 16.71
  1. Convert Ys (16.71) to LChUV's L* (48)

  2. Use this L*, and the desired hue, to set the color.

  3. Adjust saturation to keep the color "sRGB legal" meaning inside the sRGB range. Note that P3 or Adobe can be used instead, per the inpur modules in the apca-w3 package.

We're working on a new reverseAPCA() function to return one of several optional solor schemes.