Home > Article > Web Front-end > How to Find the Complementary Color of a Given Hex Code?
How to Determine the Complementary Color for a Given Color
The goal is to generate a color that is opposite to a given color. For instance, if the current color is black, the opposite should be white. This task is crucial when setting a contrasting background color for a text with a dynamic color to ensure clear visibility.
To achieve this, we employ the following approach:
Here's the code to implement this approach:
function invertColor(hex) { if (hex.indexOf('#') === 0) { hex = hex.slice(1); } // Convert 3-digit HEX to 6-digits. if (hex.length === 3) { hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]; } if (hex.length !== 6) { throw new Error('Invalid HEX color.'); } // Invert color components. var r = (255 - parseInt(hex.slice(0, 2), 16)).toString(16), g = (255 - parseInt(hex.slice(2, 4), 16)).toString(16), b = (255 - parseInt(hex.slice(4, 6), 16)).toString(16); // Pad each component with leading zeros and return. return '#' + padZero(r) + padZero(g) + padZero(b); } function padZero(str, len) { len = len || 2; var zeros = new Array(len).join('0'); return (zeros + str).slice(-len); }
Example Output:
An advanced version with a "bw" option allows you to specify whether the result should be closer to black or white, providing better contrast for improved readability:
function invertColor(hex, bw) { if (hex.indexOf('#') === 0) { hex = hex.slice(1); } // Convert 3-digit HEX to 6-digits. if (hex.length === 3) { hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]; } if (hex.length !== 6) { throw new Error('Invalid HEX color.'); } var r = parseInt(hex.slice(0, 2), 16), g = parseInt(hex.slice(2, 4), 16), b = parseInt(hex.slice(4, 6), 16); if (bw) { // Formula to determine if the color is closer to black or white. return (r * 0.299 + g * 0.587 + b * 0.114) > 186 ? '#000000' : '#FFFFFF'; } // Invert color components. r = (255 - r).toString(16); g = (255 - g).toString(16); b = (255 - b).toString(16); // Pad each component with leading zeros and return. return '#' + padZero(r) + padZero(g) + padZero(b); }
Example Output:
[](https://stackshare.io/resources/color-contrast-checker)
The above is the detailed content of How to Find the Complementary Color of a Given Hex Code?. For more information, please follow other related articles on the PHP Chinese website!