You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript准确反向推导该HSL与矩形坐标的转换公式?

从HSL亮度(L)、饱和度(S)反向推导XY坐标的方法

推导过程

已知正向转换公式:

let hsv_value = 1 - (posy / 100);
let hsv_saturation = posx / 100;
let lightness = (hsv_value / 2) * (2 - hsv_saturation);
let saturation = (hsv_value * hsv_saturation) / (1 - Math.abs(2 * lightness - 1));

设 V = hsv_value,S_hsv = hsv_saturation,L = lightness,S = saturation,反向推导步骤如下:

  1. 计算HSV的Value分量(V)
    根据L的取值分两种情况:

    • 当 L ≤ 0.5 时:
      V = L * (1 + S)
      
    • 当 L > 0.5 时:
      V = L*(1 - S) + S
      
  2. 计算HSV的Saturation分量(S_hsv)
    代入V和L的关系:

    S_hsv = 2 - (2*L)/V
    
  3. 转换为矩形内的坐标(posx, posy)

    posx = 100 * S_hsv
    posy = 100 * (1 - V)
    

代码实现(JavaScript)

function hslToPos(L, S) {
    let V;
    // 处理L为0或1的边界情况(此时饱和度无意义)
    if (L === 0 || L === 1) {
        return { posx: 0, posy: L === 0 ? 100 : 0 };
    }
    if (L <= 0.5) {
        V = L * (1 + S);
    } else {
        V = L * (1 - S) + S;
    }
    const S_hsv = 2 - (2 * L) / V;
    const posx = 100 * S_hsv;
    const posy = 100 * (1 - V);
    // 确保坐标在0-100范围内
    return {
        posx: Math.max(0, Math.min(100, posx)),
        posy: Math.max(0, Math.min(100, posy))
    };
}

注意事项

  • 当L=0(纯黑)或L=1(纯白)时,饱和度S无实际意义,此时直接返回对应边界坐标
  • 计算结果需限制在0-100区间内,避免超出矩形范围

内容的提问来源于stack exchange,提问作者atat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 19:17:36