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

Mapbox queryRenderedFeatures返回的颜色编码是什么?如何转RGBA、Hex、HSL?

Mapbox GL JS返回的归一化RGBA颜色值解析与转换

你看到的是归一化RGBA颜色编码,这是WebGL渲染管线中常用的颜色表示方式:把传统0-255范围的RGB分量和0-1范围的Alpha分量,统一映射到0-1的小数区间,方便GPU进行浮点计算。

下面是几种常见格式的转换方法:

转换为标准RGBA格式

标准RGBA的RGB分量为0-255的整数,Alpha分量保持0-1的小数(或可转换为0-100的百分比)。用JavaScript实现:

// 从queryRenderedFeatures返回的feature中提取颜色
const color = feature.layer.paint['fill-color'];

// 转换为整数RGB + 浮点Alpha的结构
const rgba = {
  r: Math.round(color.r * 255),
  g: Math.round(color.g * 255),
  b: Math.round(color.b * 255),
  a: color.a
};

// 生成CSS兼容的rgba字符串
const cssRgbaStr = `rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, ${rgba.a})`;
// 示例输出:rgba(163, 67, 42, 0.7)

转换为Hex格式

Hex格式分不带Alpha的Hex6和带Alpha的Hex8两种:

const color = feature.layer.paint['fill-color'];

// Hex6格式(无透明度)
const hex6 = `#${[
  Math.round(color.r * 255).toString(16).padStart(2, '0'),
  Math.round(color.g * 255).toString(16).padStart(2, '0'),
  Math.round(color.b * 255).toString(16).padStart(2, '0')
].join('')}`;
// 示例输出:#a3432a

// Hex8格式(带透明度)
const hex8 = `#${[
  Math.round(color.r * 255).toString(16).padStart(2, '0'),
  Math.round(color.g * 255).toString(16).padStart(2, '0'),
  Math.round(color.b * 255).toString(16).padStart(2, '0'),
  Math.round(color.a * 255).toString(16).padStart(2, '0')
].join('')}`;
// 示例输出:#a3432ab3

转换为HSL格式

HSL通过色相(0-360)、饱和度(0-100%)、亮度(0-100%)描述颜色,需先将归一化RGB转为标准RGB再计算:

// RGB转HSL工具函数
function rgbToHsl(r, g, b) {
  r /= 255;
  g /= 255;
  b /= 255;
  const max = Math.max(r, g, b);
  const min = Math.min(r, g, b);
  let h, s, l = (max + min) / 2;

  if (max === min) {
    h = s = 0; // 无色彩(灰度)
  } else {
    const delta = max - min;
    s = l > 0.5 ? delta / (2 - max - min) : delta / (max + min);
    switch (max) {
      case r: h = (g - b) / delta + (g < b ? 6 : 0); break;
      case g: h = (b - r) / delta + 2; break;
      case b: h = (r - g) / delta + 4; break;
    }
    h /= 6;
  }

  return {
    h: Math.round(h * 360),
    s: Math.round(s * 100),
    l: Math.round(l * 100),
    a: color.a
  };
}

// 执行转换
const color = feature.layer.paint['fill-color'];
const rgb = {
  r: Math.round(color.r * 255),
  g: Math.round(color.g * 255),
  b: Math.round(color.b * 255)
};
const hsl = rgbToHsl(rgb.r, rgb.g, rgb.b);

// 生成CSS兼容的hsl字符串
const cssHslStr = `hsl(${hsl.h}, ${hsl.s}%, ${hsl.l}%, ${hsl.a})`;
// 示例输出:hsl(14, 60%, 40%, 0.7)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 11:48:28