我正在尝试创建一种与当前颜色相反的颜色。我的意思是如果当前颜色是黑色,那么我需要生成白色。
其实我有一个文本(这个文本的颜色是动态的,它的颜色可以随机生成)。该文本位于 div
中,我需要为 div
的 background-color
设置与该文本相反的颜色。我希望 div
(颜色透视) 中的文本清晰。
The opposite color means: Dark / Bright
我有文本的当前颜色,我可以将它传递给这个函数:
var TextColor = #F0F0F0; // for example (it is a bright color)
function create_opp_color(current color) {
// create opposite color according to current color
}
create_opp_color(TextColor); // this should be something like "#202020" (or a dark color)
是否有创建 create_opp_color()
函数的想法?
最佳答案
更新:生产就绪代码在GitHub .
我会这样做:
- 将 HEX 转换为 RGB
- 反转 R、G 和 B 分量
- 将每个组件转换回十六进制
- 用零填充每个组件并输出。
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 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);
}
示例输出:
进阶版:
这有一个 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) {
// https://stackoverflow.com/a/3943023/112731
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 with zeros and return
return "#" + padZero(r) + padZero(g) + padZero(b);
}
示例输出:
关于javascript - 如何根据当前颜色生成相反的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35969656/