我查找了全网都查不到OKLCH()方法是颜色转换方法,那今天小编就给大家分享我的方法,可能会有点点误差,但是大体不影响。
程序员必备宝典https://tmxkj.top/#/示例:oklch(0.253267 0.015896 252.418)
得到HEX: #1b150c
十六进制整数:0x1b150c
好了,话不多说,直接上CssUtil代码!!
/*** oklch 类型颜色转换* @param oklchColor oklch(0.253267 0.015896 252.418)* @returns {string} #1b150c*/
export function convertOklchToHex(oklchColor) {// 解析 oklch 颜色值const [luminance, chroma, hue] = oklchColor.match(/(\d+\.\d+)/g).map(parseFloat);let addNum = luminance*100 +0.01// 将 oklch 转换为 rgbconst [r, g, b] = oklchToRgb(addNum, chroma, hue);// 将 rgb 转换为十六进制const hex = rgbToHex(r, g, b);return hex;
}function oklchToRgb(luminance, chroma, hue) {const l = luminance / 100;const c = chroma;const h = hue;const a = Math.cos(h * Math.PI / 180);const b = Math.sin(h * Math.PI / 180);const x = c * a;const y = c * b;const z = l - 0.299 * x - 0.114 * y;const r = x + 0.436 * z;const g = y + 0.386 * z;const b_ = 0.177 * z;return [Math.round(255 * r),Math.round(255 * g),Math.round(255 * b_)];
}function rgbToHex(r, g, b) {const componentToHex = (c) => {const hex = c.toString(16);return hex.length === 1? "0" + hex : hex;};return `#${componentToHex(r)}${componentToHex(g)}${componentToHex(b)}`;
}/*** 十六进制格式(如#bec9d4)转换为十六进制整数格式(如0x26b9f2)* @param hexColor #1b150c* @returns {string} 如0x1b150c*/
export function hexToHexInt(hexColor) {// 移除颜色字符串中的 '#' 符号const hex = hexColor.replace('#', '');// 将十六进制字符串转换为十进制整数const decimal = parseInt(hex, 16);// 返回十六进制整数格式的颜色值return (`0x${decimal.toString(16).toUpperCase()}`).toLowerCase();
}