我想将 CSS Lch 颜色字符串转换为:
--my-color: lch(20% 8.5 220.0);
转换为RGB十六进制代码。我尝试使用像Chroma的Lch解析器这样的工具,但它们似乎都使用第一坐标的绝对值(在我的情况中为20%)。
有没有一些标准的方法可以将那20%转换为大多数Lch转换工具使用的亮度值?
我想将 CSS Lch 颜色字符串转换为:
--my-color: lch(20% 8.5 220.0);
转换为RGB十六进制代码。我尝试使用像Chroma的Lch解析器这样的工具,但它们似乎都使用第一坐标的绝对值(在我的情况中为20%)。
有没有一些标准的方法可以将那20%转换为大多数Lch转换工具使用的亮度值?
JS原生的CanvasRenderingContext2D实例可以读取任何以CSS格式(字符串形式)表示的颜色,并将其写入RGBA缓冲区(0到255):
const myCssColor = "lch(20% 8.5 220.0)";
function cssColor_to_rgba255Color(string) {
const canvas = document.createElement("canvas");
canvas.width = canvas.height = 1;
const ctx = canvas.getContext("2d", {willReadFrequently: true});
ctx.fillStyle = string;
ctx.fillRect(0, 0, 1, 1);
return ctx.getImageData(0, 0, 1, 1).data;
}
const rgba = cssColor_to_rgba255Color(myCssColor);
console.log( rgba[0], rgba[1], rgba[2], rgba[3] );
// 33 51 56 255
这个函数可能性能较差,但可以通过始终回收(使用clearRect)相同的“ctx”对象来进行大幅优化。
我可以给你这个我自己写的从LCH到HEX或RGB的函数。我用PHP编写的,所以很容易适应任何其他语言。
function lch2hex($l, $c, $h) {
$a=round($c*cos(deg2rad($h)));
$b=round($c*sin(deg2rad($h)));
unset($c,$h);
// Reference white values for D65 Light Europe Observer
// $xw = 0.95047;
// $yw = 1.00000;
// $zw = 1.08883;
// Reference white values for CIE 1964 10° Standard Observer
$xw = 0.948110;
$yw = 1.00000;
$zw = 1.07304;
// Compute intermediate values
$fy = ($l + 16) / 116;
$fx = $fy + ($a / 500);
$fz = $fy - ($b / 200);
// Compute XYZ values
$x = round($xw * (($fx ** 3 > 0.008856) ? $fx ** 3 : (($fx - 16 / 116) / 7.787)),5);
$y = round($yw * (($fy ** 3 > 0.008856) ? $fy ** 3 : (($fy - 16 / 116) / 7.787)),5);
$z = round($zw * (($fz ** 3 > 0.008856) ? $fz ** 3 : (($fz - 16 / 116) / 7.787)),5);
unset($l,$a,$b,$xw,$yw,$zw,$fy,$fx,$fz);
$r = $x * 3.2406 - $y * 1.5372 - $z * 0.4986;
$g = -$x * 0.9689 + $y * 1.8758 + $z * 0.0415;
$b = $x * 0.0557 - $y * 0.2040 + $z * 1.0570;
unset($x,$y,$z);
$r = $r > 0.0031308 ? 1.055 * pow($r, 1 / 2.4) - 0.055 : 12.92 * $r;
$g = $g > 0.0031308 ? 1.055 * pow($g, 1 / 2.4) - 0.055 : 12.92 * $g;
$b = $b > 0.0031308 ? 1.055 * pow($b, 1 / 2.4) - 0.055 : 12.92 * $b;
$r = round(max(min($r, 1), 0) * 255);
$g = round(max(min($g, 1), 0) * 255);
$b = round(max(min($b, 1), 0) * 255);
return '#' . sprintf('%02X%02X%02X', $r, $g, $b);
}