What is the formula for getting the most contrasting color for the specified color?

258 Views Asked by At

I write an application where there is a need to get second color having big contrast from the input color. So the contrast between 2 colors must be more than or equal to 7. Does anyone know a working formula? I have found some questions about this topic, but none of the answers is working for me.

1

There are 1 best solutions below

0
On

I asked Bard AI, while its anwsers don't work for gray colors like rgb(127,127,127), so I revised one of the anwsers, here is it:

/**
 * get contrast color in monochrome
 * @param {Array<number>} rgb - rgb channels, 0~255
 * @param {number} maxContrast 128~255
 * @returns {Array<number>}
 */
function getContrastColor([r, g, b], maxContrast = 192) {
  const minContrast = 128;
  let y = Math.round(0.299 * r + 0.587 * g + 0.114 * b); // luma
  let oy = 255 - y; // opposite
  let dy = oy - y; // delta
  if (Math.abs(dy) > maxContrast) {
    dy = Math.sign(dy) * maxContrast;
    oy = y + dy;
  } else if (Math.abs(dy) < minContrast) {
    dy = Math.sign(dy) * minContrast;
    oy = y + dy;
  }
  return [oy, oy, oy];
}

And some test results:

getContrastColor([0,0,0]) // [192, 192, 192]
getContrastColor([255,0,0]) // [204, 204, 204]
getContrastColor([127,127,127]) // [255, 255, 255]
getContrastColor([128,128,128]) // [0, 0, 0]
getContrastColor([255,255,0]) // [34, 34, 34]
getContrastColor([255,255,255]) // [63, 63, 63]

You may set maxContrast to 255 as needed.