将CSS OKLCH颜色转换为十六进制HEX颜色和十六进制整数格式

我查找了全网都查不到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 转换为 rgb
    const [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();
}
相关推荐
IT_陈寒4 分钟前
Redis内存警告竟是因为这个不起眼的配置项
前端·人工智能·后端
lilian2335 分钟前
Harmony os 技术实战|拼豆制图43:压缩字符矩阵上线前如何拦住错位图纸
开发语言·前端·华为·矩阵·harmonyos
kyriewen40 分钟前
我踩了3次同一个坑才明白:JavaScript里比0.1+0.2更隐蔽的5个数字陷阱
前端·javascript·面试
徐小夕1 小时前
表格、文档、甘特、大屏、表单一站打通:pxcharts超级表格4.0正式上线!
前端·算法·github
用户594404103561 小时前
Vue3 + TypeScript + Leaflet.js 实战:构建企业级地理信息应用
前端
kyson_1 小时前
一次搭好 ESLint + Prettier + Husky + lint-staged 前端代码工作流
前端
zhifou1234561 小时前
Vue基础(二)
前端·javascript·vue.js
两只羊ovo2 小时前
手写一个最小版 Claude Code:从任务拆解到 Agent Loop 转起来
前端
给个offer养家糊口2 小时前
抽离 elpis npm 包
前端
默_笙2 小时前
🙃 我让爬虫终于看到了我的网站,后端同事说"这也行?"(下):App Router 全栈实战
前端·javascript