我需要一个将颜色作为输入的函数,该颜色是文本的背景颜色。根据给定的颜色,该函数应返回白色或黑色,可用作文本颜色以获得最佳对比度。
我曾经从互联网上复制了下面的函数,它非常适合作为输入的 hex color 字符串。 现在需求变了,我想把这个函数转换为hsl中的输入值。输入不应该再是颜色格式的字符串,而只是 hsl 值,例如:
getContrastTextColor(h, s, l)
。
看起来很简单,但我不知道该怎么做。问题不在于 Javascript,而在于逻辑。
function getContrastTextColor(hex)
{
/*
From this W3C document: http://www.webmasterworld.com/r.cgi?f=88&d=9769&url=http://www.w3.org/TR/AERT#color-contrast
Color brightness is determined by the following formula:
((Red value X 299) + (Green value X 587) + (Blue value X 114)) / 1000
*/
const threshold = 130; /* about half of 256. Lower threshold equals more dark text on dark background */
const hRed = hexToR(hex);
const hGreen = hexToG(hex);
const hBlue = hexToB(hex);
function hexToR(h) { return parseInt((cutHex(h)).substring(0, 2), 16) }
function hexToG(h) { return parseInt((cutHex(h)).substring(2, 4), 16) }
function hexToB(h) { return parseInt((cutHex(h)).substring(4, 6), 16) }
function cutHex(h) { return (h.charAt(0) == "#") ? h.substring(1, 7) : h }
const cBrightness = ((hRed * 299) + (hGreen * 587) + (hBlue * 114)) / 1000;
if (cBrightness > threshold) { return "#000000"; } else { return "#ffffff"; }
}
嗯,之前有一个答案, 您可以在此处查看代码。
只需将 hsl 转换为十六进制即可。
function hslToHex(h, s, l) {
l /= 100;
const a = s * Math.min(l, 1 - l) / 100;
const f = n => {
const k = (n + h / 30) % 12;
const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
return Math.round(255 * color).toString(16).padStart(2, '0'); // convert to Hex and prefix "0" if needed
};
return `#${f(0)}${f(8)}${f(4)}`;
}
然后获取十六进制值,然后使用您之前的代码。
const hex = hslToHex(h, s, l)
/* rest of the code . . . */