I wanted to convert a CSS Lch color string like:
--my-color: lch(20% 8.5 220.0);
To an RGB hex code. I tried using tools like chroma's Lch parser, but all of them seem to use absolute values for the first ordinate (the 20% in my case).
Is there some standard way to convert that 20% into the lightness values used by most Lch conversion tools?
A JS-native CanvasRenderingContext2D instance can read any CSS-formatted color (as a string) and write it in a RGBA buffer (0 to 255) for you :
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
This function may have poor performance but can be greatly optimized by always recycling (using clearRect) the same "ctx" object.
The w3c is working on a draft and there is example code in javascript attached (it's a bit too long to post here and you'll need higher math to do that (at least sin and the power of 2.4).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With