Generating the Opposite Color from Given Color
Determining the opposite color from a given color is a frequent requirement in web and graphic design. This becomes crucial when the text color is dynamic and the background color needs to be adjusted for readability. Our goal is to create a function that takes the current color and generates its opposite, resulting in a color that provides high contrast and clear text visibility.
An Algorithm for Generating the Opposite Color
To achieve our objective, we propose the following algorithm:
Implementing the Algorithm in JavaScript
Below is a JavaScript implementation of the outlined algorithm:
function invertColor(hex) { if (hex.indexOf('#') === 0) { hex = hex.slice(1); } 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 = (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); 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 accepts a HEX color code and returns its opposite color. For example, if we supply the color "#F0F0F0", we will get "#0F0F0F" as the opposite color.
Advanced Option: Considering Brightness
In some cases, it may be necessary to consider the brightness of the color when generating its opposite. Here's a modified version of the function that includes a bw parameter:
function invertColor(hex, bw) { if (hex.indexOf('#') === 0) { hex = hex.slice(1); } 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) { return (r * 0.299 + g * 0.587 + b * 0.114) > 186 ? '#000000' : '#FFFFFF'; } r = (255 - r).toString(16); g = (255 - g).toString(16); b = (255 - b).toString(16); return '#' + padZero(r) + padZero(g) + padZero(b); }
If the bw parameter is set to true, the function will return black if the given color is light (#000000) and white if it is dark (#FFFFFF). Otherwise, it will generate the opposite color as before.
The above is the detailed content of How to Generate the Opposite Color of a Given Hex Code?. For more information, please follow other related articles on the PHP Chinese website!