Problem:
How can I create a color that is opposite to the current color in terms of lightness or darkness? If the current color is black, I need to generate white, and vice versa.
Solution:
To achieve this functionality, we can utilize an algorithm that involves the following steps:
By following these steps, we can create a function named invertColor that takes a current HEX color as input and returns its opposite color:
function invertColor(hex) { // Convert HEX to RGB var r = parseInt(hex.slice(1, 3), 16); var g = parseInt(hex.slice(3, 5), 16); var b = parseInt(hex.slice(5, 7), 16); // Invert color components r = (255 - r).toString(16); g = (255 - g).toString(16); b = (255 - b).toString(16); // Pad each with 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); }
This function takes into account the need to invert colors to create opposite shades of lightness or darkness.
Example:
If we pass the color "#F0F0F0" (a bright color) as an input to the invertColor function, it would return "#202020" (a dark color).
The above is the detailed content of How do you generate the opposite color of a given color in terms of light or dark?. For more information, please follow other related articles on the PHP Chinese website!