将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();
}
相关推荐
Mr_Mao2 小时前
Naive Ultra:中后台 Naive UI 增强组件库
前端
前端小趴菜054 小时前
React-React.memo-props比较机制
前端·javascript·react.js
摸鱼仙人~5 小时前
styled-components:现代React样式解决方案
前端·react.js·前端框架
sasaraku.5 小时前
serviceWorker缓存资源
前端
RadiumAg6 小时前
记一道有趣的面试题
前端·javascript
yangzhi_emo6 小时前
ES6笔记2
开发语言·前端·javascript
yanlele7 小时前
我用爬虫抓取了 25 年 5 月掘金热门面试文章
前端·javascript·面试
中微子8 小时前
React状态管理最佳实践
前端
烛阴8 小时前
void 0 的奥秘:解锁 JavaScript 中 undefined 的正确打开方式
前端·javascript
中微子8 小时前
JavaScript 事件与 React 合成事件完全指南:从入门到精通
前端