给定HSL中的某一种颜色(假设hsl(74,64%,59%)),我想要计算什么较暗的阴影(具有相同的h和s值)给我足够的对比度来满足W3C颜色对比度要求。
有一些公式可以将HSL转换为RGB (例如https://en.wikipedia.org/wiki/HSL_and_HSV#HSL_to_RGB),并根据该RGB计算相对亮度(例如https://www.w3.org/TR/WCAG20/#relativeluminancedef)。根据颜色对比度公式(https://www.w3.org/TR/WCAG20/#contrast-ratiodef),我可以计算另一种颜色的相对亮度。
然而,然后我就卡住了。我找不到从给定的相对亮度返回到给定h和s的HSL颜色的方法。
使用像https://contrast-ratio.com/这样的工具,我可以降低亮度,直到它满足要求,但我想要一个公式(最好是在JavaScript中)来对大量的颜色进行计算。
(我目前正在使用二进制搜索方法来查找最接近的值,通过测试从HSL到RGB到相对亮度的许多转换,但这是相当密集的,而且我想知道在两者之间转换到RGB是否会引入不准确。)
发布于 2020-05-13 05:03:15
希望这就是你所需要的
使用此SO answer及以下内容中的公式:
// Relative luminance calculations
function adjustGamma(p) {
if (p <= 0.03928) {
return p / 12.92;
} else {
return Math.pow( ( p + 0.055 ) / 1.055, 2.4 );
}
}
function relativeLuminance(rgb) {
const r = adjustGamma( rgb[0] / 255 );
const g = adjustGamma( rgb[1] / 255 );
const b = adjustGamma( rgb[2] / 255 );
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}
// Contrast calculations
function contrastRatio(a,b) {
const ratio = (a + 0.05) / (b + 0.05);
return ratio >= 1 ? ratio : 1 / ratio;
}
// Loop for correct lightness
function rgbFromHslContrast(h, s, l1, ratio) {
var inc = -0.01;
var l2 = ( ( l1 + 0.05 ) / ratio - 0.05 );
if (l2 < 0) {
l2 = ( ratio * ( l1 + 0.05 ) - 0.05 );
inc = -inc;
}
while (contrastRatio(l1, relativeLuminance(hslToRgb(h, s, l2))) < ratio) {
l2 += inc;
}
return hslToRgb(h, s, l2);
}您要调用的函数为:
const originalHslAsRgb = hslToRgb(0.2, 0.2, 0.2);
const l1 = relativeLuminance(originalHslAsRgb);
const contrastRgb = rgbFromHslContrast(0.2, 0.2, l1, 3.5) // 3.5 is minimum contrast factor we target for..
// [139, 149, 100]
// equivalent to hsl(72, 20%, 53%)https://stackoverflow.com/questions/61525100
复制相似问题