如何确定给定颜色的补色
目标是生成与给定颜色相反的颜色。例如,如果当前颜色是黑色,则相反的颜色应该是白色。当为具有动态颜色的文本设置对比背景色以确保清晰可见时,此任务至关重要。
为了实现这一点,我们采用以下方法:
以下是实现此方法的代码:
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); }
示例输出:
带有“bw”选项的高级版本允许您指定结果是否应该更接近黑色或白色,提供更好的对比度以提高可读性:
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); }
示例输出:
[](https://stackshare.io/resources/color-contrast-checker)
以上是如何找到给定十六进制代码的补色?的详细内容。更多信息请关注PHP中文网其他相关文章!