@basiclines/rampa-sdk

中文文档
6.0.0发布于 2026/03/21MITTypeScriptES Module构建来源已验证近 30 天下载 2.5万

程序化 JavaScript SDK 用于生成带有斜坡的调色板

中文使用文档
文档目录37 节
  1. 安装
  2. 香草JS( CDN / 脚本标签)
  3. 快速启动
  4. API 密码
  5. rampa(baseColor)
  6. 构建方法
  7. 访问颜色
  8. 产出方法
  9. color(input)
  10. rampa.convert(color, format)
  11. rampa.mix(color1, color2, t)
  12. lint(foreground, background)
  13. 类型
  14. 实例
  15. 设计系统调色板
  16. 配有和谐的全调色板
  17. 主题的 CSS 变量
  18. 构建工具集成
  19. CLI 对等
  20. 颜色空格
  21. LinearColorSpace
  22. PlaneColorSpace
  23. CubeColorSpace
  24. 内插模式
  25. 分布曲线
  26. 颜色访问器
  27. 图像调色板提取
  28. palette(filePath)
  29. 主要颜色
  30. 原始调色板
  31. ANSI 调色板
  32. 由 OKLCH 属性分组
  33. 排序与 .sortBy()
  34. 额外
  35. 产出
  36. 调色板 Entry 形状
  37. 发展

兰帕 SDK

程序JavaScript/TypeScript SDK用于生成数学精确,可访问的色调调板. 和引擎一样 兰帕CLI,用于应用,构建工具和设计系统.

安装

npm install @basiclines/rampa-sdk

香草JS( CDN / 脚本标签)

每条上都有预建的浏览器捆绑 GitHub 发布。不需要捆绑工或建造步骤,只要放下 <script> 标签 :

<script src="https://github.com/basiclines/rampa-studio/releases/latest/download/rampa-sdk.min.js"></script>
<script>
  // Everything is available under the global `Rampa` object
  const palette = Rampa.rampa('#3b82f6').size(5);
  console.log('' + palette(1));   // first color
  console.log(palette.palette);   // all colors

  const css = Rampa.rampa('#3b82f6').output('css');
  const mixed = Rampa.rampa.mix('#ff0000', '#0000ff', 0.5);

  const linear = new Rampa.LinearColorSpace('#ffffff', '#000000').size(10);
  console.log('' + linear(5)); // midpoint gray

  const c = Rampa.color('#3b82f6');
  console.log(c.hex, c.rgb, c.luminance);
</script>

通过替换来固定一个特定的版本 latest 标记名称 :

https://github.com/basiclines/rampa-studio/releases/download/v3.0.0/rampa-sdk.min.js

快速启动

import { rampa } from '@basiclines/rampa-sdk';

// Generate a 10-color palette from blue
const palette = rampa('#3b82f6');
palette(1)            // first color (ColorAccessor)
palette(5).oklch()    // format conversion

// Custom size with lightness range
const custom = rampa('#3b82f6').size(5).lightness(10, 90);
custom(3)             // third color

// Add complementary harmony
const harmonies = rampa('#3b82f6').add('complementary');
harmonies.ramps       // [base, complementary]

// Output as CSS variables
const css = rampa('#3b82f6').output('css');

API 密码

rampa(baseColor)

创建可调用的调色板。 接受任何有效的 CSS 颜色( hex, hsl, rgb, oklch, 命名为颜色) 。 所有方法在任何顺序上都是可连锁的,结果总是以基于1的指数调用.

const palette = rampa('#3b82f6');
const palette = rampa('rgb(59, 130, 246)');
const palette = rampa('hsl(217, 91%, 60%)');
const palette = rampa('oklch(62.3% 0.214 259)');

palette(1)           // first color
palette(5).hsl()     // format conversion
palette.palette      // string[] of all colors

构建方法

所有构建器方法都返回同样的可调用,用于链条按任何顺序排列.

.size(steps)

调色板中的颜色数量(2-100,默认为:10).

rampa('#3b82f6').size(5);

.format(type)

输出值的颜色格式 : hex, (中文(简体) ), hsl, (中文(简体) ), rgb, (中文(简体) ), oklch (默认 : hex) (中文(简体) ).

rampa('#3b82f6').format('hsl');
// palette(1) → 'hsl(0, 0%, 0%)', palette(2) → 'hsl(212, 69%, 25%)', ...

.lightness(start, end)

光度范围为0-100(默认为:0,100).

rampa('#3b82f6').lightness(10, 90);

.saturation(start, end)

饱和度范围为0-100(默认:100,0).

rampa('#3b82f6').saturation(80, 20);

.hue(start, end)

相位相位相位相位相位相位相位相位相位相位相位相位相位相位相位相位相位相位相位相位相位相相位相位相位相位相相相位相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相.

rampa('#3b82f6').hue(-30, 30);

.lightnessDistribution(type), (中文(简体) ), .saturationDistribution(type), (中文(简体) ), .hueDistribution(type)

每个信道的分布曲线( 默认值 : linear) (中文(简体) ).

可用分布 : linear, (中文(简体) ), geometric, (中文(简体) ), fibonacci, (中文(简体) ), golden-ratio, (中文(简体) ), logarithmic, (中文(简体) ), powers-of-2, (中文(简体) ), musical-ratio, (中文(简体) ), cielab-uniform, (中文(简体) ), ease-in, (中文(简体) ), ease-out, (中文(简体) ), ease-in-out

rampa('#3b82f6')
  .lightnessDistribution('fibonacci')
  .saturationDistribution('ease-out')
  .hueDistribution('golden-ratio');

.tint(color, opacity, blend?)

在调色板上涂上颜色.

  • color - 任何有效的 CSS 颜色
  • opacity - 丁强度0-100
  • blend — 混合模式(默认 : normal(中文(简体) )

可用的混合模式 : normal, (中文(简体) ), multiply, (中文(简体) ), screen, (中文(简体) ), overlay, (中文(简体) ), darken, (中文(简体) ), lighten, (中文(简体) ), color-dodge, (中文(简体) ), color-burn, (中文(简体) ), hard-light, (中文(简体) ), soft-light, (中文(简体) ), difference, (中文(简体) ), exclusion, (中文(简体) ), hue, (中文(简体) ), saturation, (中文(简体) ), color, (中文(简体) ), luminosity, (中文(简体) ), plus-darker, (中文(简体) ), plus-lighter

rampa('#3b82f6')
  .tint('#FF0000', 15, 'overlay');

.add(type) 编号 : .add('shift', degrees)

增加和谐坡道. 能被多相唤.

可用的和谐类型 :

  • complementary ——相对相色相轮(+180°)
  • triadic - 3个颜色,相隔120°
  • analogous 相邻颜色,相隔30°
  • split-complementary 相向相近的2个颜色
  • square - 4个颜色,相隔90°
  • compound ——补充+拆分
  • shift ——自定义以 N 度旋转
rampa('#3b82f6')
  .add('complementary')
  .add('triadic')
  .add('shift', 45);

访问颜色

调用基于 1 的调色板索引以获取 ColorAccessor数字 :

const palette = rampa('#3b82f6').size(5).lightness(10, 90);

palette(1)           // ColorAccessor — first color
palette(3).hsl()     // format conversion
palette(5).oklch()   // any format
`${palette(1)}`      // works in template literals

palette.palette      // string[] of all colors
palette.ramps        // RampResult[] (base + harmonies)

产出方法

.output(format, prefix?)

导出调色板为 'css', (中文(简体) ), 'json',或 'text'可选 prefix 设置变量/缩写名称( 默认 : 'base') (中文(简体) ).

// CSS custom properties
rampa('#3b82f6').size(5).output('css', 'primary');
// :root {
//   /* primary */
//   --primary-0: #000000;
//   --primary-1: #143d6b;
//   --primary-2: #4572ba;
//   --primary-3: #b1b9ce;
//   --primary-4: #ffffff;
// }

// JSON
rampa('#3b82f6').size(5).output('json', 'primary');
// {
//   "ramps": [
//     {
//       "name": "primary",
//       "baseColor": "#3b82f6",
//       "colors": ["#000000", "#143d6b", "#4572ba", "#b1b9ce", "#ffffff"]
//     }
//   ]
// }

// Plain text (one color per line)
rampa('#3b82f6').size(5).output('text');
// #000000
// #143d6b
// #4572ba
// #b1b9ce
// #ffffff

.ramps 编号 : .palette

直接作为属性访问生成的坡道和颜色 :

const result = rampa('#3b82f6').size(5).add('complementary');
result.palette                // base ramp colors: ['#000000', '#143d6b', ...]
result.ramps                  // all ramps: [{ name: 'base', ... }, { name: 'complementary', ... }]
result.ramps[1].colors        // complementary ramp colors

color(input)

检查,转换,混合,并导出单一颜色. 等值为 rampa color 在CLI中.

使用所有属性值 0-1 正常范围 匹配 CSS 规格公约:

财产范围
hsl.h0-360 (度) (中文(简体) )
hsl.s, (中文(简体) ), hsl.l0 - 1 个
oklch.l0 - 1 个
oklch.c0-0.4(本地OKLCH比例)
oklch.h0-360 (度) (中文(简体) )
import { color } from '@basiclines/rampa-sdk';

const c = color('#fe0000');
c.hex              // '#fe0000'
c.rgb              // { r: 254, g: 0, b: 0 }
c.hsl              // { h: 0, s: 1.0, l: 0.5 }
c.oklch            // { l: 0.628, c: 0.258, h: 29 }
c.luminance        // 0.628

// Format conversion (string output uses CSS conventions: percentages)
c.format('hsl')    // 'hsl(0, 100%, 50%)'
c.format('rgb')    // 'rgb(254, 0, 0)'
c.format('oklch')  // 'oklch(62.8% 0.258 29)'

// Export
c.output('json')           // JSON with all formats
c.output('css', 'brand')   // CSS custom properties with prefix
c.output('text')           // plain hex string

// String coercion
`${c}`             // '#fe0000'

颜色变换

所有变换都在 OKLCH 空间 并返回一个新的不可改变 Color自由的链条.

// Absolute deltas — clamped to valid range
c.lighten(0.1)           // L += 0.1 (OKLCH lightness, 0-1)
c.darken(0.1)            // L -= 0.1
c.saturate(0.05)         // C += 0.05 (OKLCH chroma)
c.desaturate(0.05)       // C -= 0.05
c.rotate(30)             // H += 30° (hue rotation)

// All accept negative values: lighten(-0.1) === darken(0.1)

// Set absolute OKLCH values
c.set({ lightness: 0.48 })             // set L
c.set({ chroma: 0.15, hue: 200 })     // batch set

// Chain transforms
color('#66b172').lighten(0.1).desaturate(0.05).hex
// → bright desaturated green, no throwaway converters

混合( 彩色空间插值)

像CSS一样 color-mix() ——将两种颜色相插于所选颜色空间.

c.mix('#0000ff', 0.5)            // 50% mix in oklch (default)
c.mix('#0000ff', 0.18, 'lab')    // explicit color space
c.mix('#0000ff', 0.18, 'srgb')   // sRGB interpolation

组合( 组合模式)

如Photoshop/CSS混合模式——复合材料有两种颜色并带有不透明与混合模式.

c.blend('#0000ff', 0.15, 'multiply')
c.blend('#0000ff', 0.15, 'screen')
c.blend('#0000ff', 0.15, 'overlay')

可用的混合模式 : normal, (中文(简体) ), multiply, (中文(简体) ), screen, (中文(简体) ), overlay, (中文(简体) ), darken, (中文(简体) ), lighten, (中文(简体) ), color-dodge, (中文(简体) ), color-burn, (中文(简体) ), hard-light, (中文(简体) ), soft-light, (中文(简体) ), difference, (中文(简体) ), exclusion, (中文(简体) ), hue, (中文(简体) ), saturation, (中文(简体) ), color, (中文(简体) ), luminosity, (中文(简体) ), plus-darker, (中文(简体) ), plus-lighter

rampa.convert(color, format)

将颜色转换成不同格式的独立工具.

rampa.convert('#fe0000', 'hsl');    // 'hsl(0, 100%, 50%)'
rampa.convert('#fe0000', 'rgb');    // 'rgb(254, 0, 0)'
rampa.convert('#fe0000', 'oklch');  // 'oklch(62.8% 0.257 29)'
rampa.convert('#fe0000', 'hex');    // '#fe0000'

rampa.mix(color1, color2, t)

在 OKLCH 空间中以一定比例混合两种颜色。 出产能感知到统一过渡——胡同会自然地行走相色相轮,光度阶向外看均匀,克罗玛会保持生动活泼地活活地活活地活活地活活地活活地活活地活活地活活活地活活活地活活活地活活活地活活活地活活活地活活活地活活活活活地活活活活活地活活活活地活活活活地活活活活地活活活活活地活活活活地活活活活活地活活活活地活活活活地活活活活活活活地活活活活地活活活活活地活活活活地活活活活活活地活活活活地活活活活活活活活地活活活活活活活活活活活活活活活活活活活活活活活活活活活活活活活活活活活活活活活活活活活活活活活活活活活活活活活活活活活活活活活活活活活.

rampa.mix('#ff0000', '#0000ff', 0);    // '#ff0302' (start color)
rampa.mix('#ff0000', '#0000ff', 0.5);  // midpoint — vivid purple, not muddy gray
rampa.mix('#ff0000', '#0000ff', 1);    // '#0031e5' (end color)
rampa.mix('#000000', '#ffffff', 0.5);  // perceptual mid-gray

生成带有多步的梯度 :

const steps = 10;
const gradient = Array.from({ length: steps }, (_, i) =>
  rampa.mix('#ff0000', '#0000ff', i / (steps - 1))
);

lint(foreground, background)

评价两种颜色之间的对比。 返回分数、通过/失败级别和提示警告。 默认模式是 'apca'。 。 。 .

import { lint } from '@basiclines/rampa-sdk';

// APCA (default) — returns Lc value
const result = lint('#ffffff', '#1e1e2e');
result.score      // -104.3 (Lc value)
result.pass       // true (at least one level passes)
result.levels     // [{ name: 'Preferred body text', threshold: 90, pass: true }, ...]
result.warnings   // []

// WCAG 2.x — chain .mode('wcag')
const wcag = lint('#777', '#ffffff').mode('wcag');
wcag.score        // 4.48 (contrast ratio)
wcag.levels       // [{ name: 'AAA Normal text', threshold: 7, pass: false }, ...]

// Export
result.output('json')  // JSON with full result
result.output('text')  // readable text report
result.output('css')   // CSS custom properties

线性警告 自动开火 :

  • 近同种颜色( deltaE < 3)
  • 低于最低可用阈值的对比
  • 纯 #000000 或者说 #ffffff 检测

类型

import type {
  ColorFormat,         // 'hex' | 'hsl' | 'rgb' | 'oklch'
  ScaleType,           // 'linear' | 'fibonacci' | 'golden-ratio' | ...
  BlendMode,           // 'normal' | 'multiply' | 'screen' | ...
  HarmonyType,         // 'complementary' | 'triadic' | 'analogous' | ...
  RampResult,          // { name, baseColor, colors }
  RampaResult,         // { ramps: RampResult[] }
  RampaFn,             // callable palette returned by rampa()
  Color,               // { hex, rgb, hsl, oklch, luminance, format(), output(), lighten(), ... }
  ColorInfo,           // { hex, rgb, hsl, oklch }
  OklchSetValues,      // { lightness?, chroma?, hue? } for color.set()
  InterpolationMode,   // 'oklch' | 'lab' | 'rgb' | 'srgb'
  LinearColorSpaceFn,  // callable function returned by LinearColorSpace.size()
  CubeColorSpaceFn,    // callable function returned by CubeColorSpace.size()
  LintResult,          // lint builder with score, pass, levels, warnings, output()
  ContrastMode,        // 'wcag' | 'apca'
  ContrastLevelResult, // { name, threshold, pass }
  ContrastResult,      // { mode, score, pass, levels, warnings, foreground, background }
} from '@basiclines/rampa-sdk';

实例

设计系统调色板

import { rampa } from '@basiclines/rampa-sdk';

const primary = rampa('#3b82f6')
  .size(10)
  .lightness(5, 95)
  .saturationDistribution('ease-out');

const neutral = rampa('#64748b')
  .size(10)
  .saturation(20, 0);

const danger = rampa('#ef4444')
  .size(10)
  .lightness(10, 90);

// Access individual colors
primary(5)         // mid-tone blue
neutral(1)         // darkest gray
danger(8).hsl()    // light red in HSL

配有和谐的全调色板

const palette = rampa('#3b82f6')
  .size(10)
  .lightness(5, 95)
  .lightnessDistribution('ease-in-out')
  .add('complementary')
  .add('analogous');

palette(1)          // first base color
palette.ramps[1]    // complementary ramp
palette.ramps[2]    // analogous ramp

主题的 CSS 变量

const theme = rampa('#3b82f6')
  .size(10)
  .add('complementary')
  .tint('#FFD700', 5, 'overlay')
  .output('css');

// Inject into page
const style = document.createElement('style');
style.textContent = theme;
document.head.appendChild(style);

构建工具集成

import { rampa } from '@basiclines/rampa-sdk';
import { writeFileSync } from 'fs';

const colors = rampa('#3b82f6')
  .size(10)
  .format('hsl');

// Write to a tokens file
writeFileSync('tokens.json', JSON.stringify({ colors: colors.palette }, null, 2));

CLI 对等

SDK输出与CLI相同. 这些是等同的:

# CLI
rampa --color "#3b82f6" --size=5 --lightness 10:90 --add=complementary --output json
// SDK
rampa('#3b82f6').size(5).lightness(10, 90).add('complementary').output('json');

颜色空格

色彩空间允许您从一组锚地颜色中创建结构化调色板,并进行分解查询. 现有三种几何原始:

  • 线性颜色空间 1D内插坡道
  • 平面颜色空间 - 二维饱和相光平面
  • 立方体颜色空间 3D 三线插值立方体

LinearColorSpace

将两种颜色之间插入来产生平平相间的斜坡.

import { LinearColorSpace } from '@basiclines/rampa-sdk';

const neutral = new LinearColorSpace('#ffffff', '#000000').size(24);
neutral(1)               // → '#ffffff' (lightest, returns string directly)
neutral(12)              // → '#666666' (mid gray)
neutral(12).hsl()        // → 'hsl(0, 0%, 40%)'
neutral.palette          // → string[24]

随机回顾

完全进入单个步骤 Color 对象为 .at(),或与 .colors()数字 :

const ramp = new LinearColorSpace('#000', '#fff').size(12);

ramp.at(3)                       // → Color (0-based index)
ramp.at(3).oklch.c               // → chroma at step 3
ramp.at(3).lighten(0.1).hex      // → transform a ramp step

ramp.colors()                    // → Color[]
ramp.colors().map(c => c.oklch.c)  // → chroma curve across ramp

.at() 以 0 为基础 (比如说) Array.at()),而可调用 ramp(n) 仍然是基于1的后向兼容性.

查找表格模式

设定 .interpolation(false) 对于一个简单的查询表——没有插入,只是索引了您提供的确切颜色:

const base = new LinearColorSpace(
  '#45475a', '#f38ba8', '#a6e3a1', '#f9e2af',
  '#89b4fa', '#f5c2e7', '#94e2d5', '#a6adc8'
).interpolation(false).size(8);

base(1)  // → '#45475a' (exact, no interpolation)
base(3)  // → '#a6e3a1'

PlaneColorSpace

创建用于单色调的2D色平面,以共享暗/光值为锚. 每架制造一架飞机.

Y(lightness)
1 │  light ─────────── hue
  │    │                 │
  │    │   interpolated  │
  │    │                 │
0 │  dark ─────────── dark
  └──────────────────────── X(saturation)
      0                  1

在Y=0时,整行会汇合到暗锚.

import { PlaneColorSpace } from '@basiclines/rampa-sdk';

// One plane per hue, reuse dark/light anchors
const red  = new PlaneColorSpace('#1e1e2e', '#cdd6f4', '#f38ba8').size(6);
const blue = new PlaneColorSpace('#1e1e2e', '#cdd6f4', '#89b4fa').size(6);

red(3, 5)          // → ColorAccessor (saturation=3, lightness=5)
red(0, 3)          // → achromatic at lightness 3 (no hue influence)
red(5, 5)          // → full hue color
red(0, 0)          // → dark anchor
red.palette        // → string[36] (6²)

// Ramp introspection
red.at(3, 5)              // → Color at (saturation=3, lightness=5)
red.at(3, 5).oklch.c      // → chroma at that coordinate
red.colors()              // → Color[] (flat, row-major)

// Template literals and concatenation work directly
`background: ${red(3, 5)};`  // → 'background: #ab34cd;'

// Format conversion
red(3, 5).hsl()    // → 'hsl(280, 60%, 50%)'
red(3, 5).oklch()  // → 'oklch(52.3% 0.198 310)'

CubeColorSpace

通过三线插入从8个角色创建出3D色立方体. 构造器密钥成为语义外观的别名.

import { CubeColorSpace } from '@basiclines/rampa-sdk';

const { r, b, tint } = new CubeColorSpace({
  k: '#1e1e2e',    // origin (0,0,0)
  r: '#f38ba8',    // x axis
  g: '#a6e3a1',    // y axis
  b: '#89b4fa',    // z axis
  y: '#f9e2af',    // x+y
  m: '#cba6f7',    // x+z
  c: '#94e2d5',    // y+z
  w: '#cdd6f4',    // x+y+z
}).size(6);

r(4)                     // → strong red
tint({ r: 4, b: 2 })     // → red-blue blend
tint({ w: 3 })           // → mid-white (all axes at 3)

// Ramp introspection
cube.at(2, 3, 1)         // → Color at (x=2, y=3, z=1)
cube.colors()            // → Color[]

自定义词汇

化名是指您在构建器中设置的任何名称——不限于ANSI名称:

const space = new CubeColorSpace({
  dark:    '#1a1a2e',
  warm:    '#e74c3c',
  nature:  '#2ecc71',
  ocean:   '#3498db',
  sunset:  '#f39c12',
  berry:   '#9b59b6',
  mint:    '#1abc9c',
  light:   '#ecf0f1',
}).size(6);

space({ warm: 4, ocean: 2 })  // → warm-ocean blend

如何用别名映射到立方体

以插入顺序显示的立方角 8 个密钥映射 :

职位键 #立方体编码轴口口罩
第1个来源(0起,0起)—— 说
第二届页:1(1 0 0) (中文(简体) )页:1
第三届尔(0,1,0) (中文(简体) )尔
第四届页:1(0,0,1个)页:1
第五届页:1(1,1,0美元)页:1
第六届页:1(1 0,1) (中文(简体) )x+z 组合键
第七届对(0,1,1) (单位:千美元)y+z 键
第八届日记(单位:1,1)x+y+z 时

当你打电话 tint({ r: 4, b: 2 }),每个别名的口罩会被其强度乘以相加,并与 Math.max 生成立方体坐标.

内插模式

LinearColorSpace, (中文(简体) ), PlaneColorSpace,以及 CubeColorSpace 所有支持可配置插值 :

模式说明
'oklch' (默认)观念上的统一——胡同会穿梭于相色相轮上,甚至有轻快的步道
'lab'CIE L*a*b*——感知而无色相旋转
'rgb'线性 RGB — 快速但概念上不平衡
false无插值——平面检索表(仅限亮相空间)
// LinearColorSpace
new LinearColorSpace('#ff0000', '#0000ff').interpolation('oklch').size(10)
new LinearColorSpace('#ff0000', '#0000ff').interpolation('lab').size(10)
new LinearColorSpace('#f00', '#0f0', '#00f').interpolation(false).size(3)

// PlaneColorSpace
new PlaneColorSpace('#000', '#fff', '#f00').interpolation('oklch').size(6)
new PlaneColorSpace('#000', '#fff', '#f00').interpolation('lab').size(6)

// CubeColorSpace
new CubeColorSpace({ ... }).interpolation('lab').size(6)

分布曲线

所有颜色空间类支持 .distribution(scale) 以应用非线性相距。 未设置时, 步骤间距均匀( 在默认路径上为零 ) .

可用天平 : ease-in, (中文(简体) ), ease-out, (中文(简体) ), ease-in-out, (中文(简体) ), fibonacci, (中文(简体) ), golden-ratio, (中文(简体) ), geometric, (中文(简体) ), logarithmic, (中文(简体) ), powers-of-2, (中文(简体) ), musical-ratio, (中文(简体) ), cielab-uniform

// Ease-in: bunch colors toward the start, spread out toward the end
const ramp = new LinearColorSpace('#ffffff', '#000000')
  .distribution('ease-in')
  .size(10);

// Fibonacci spacing on a 2D plane
const red = new PlaneColorSpace('#1e1e2e', '#cdd6f4', '#f38ba8')
  .distribution('fibonacci')
  .size(8);

// Golden ratio on a cube
const space = new CubeColorSpace({ ... })
  .distribution('golden-ratio')
  .size(6);

颜色访问器

所有颜色空格查找返回 a ColorAccessor ——一个直接在模板字面和通配上工作的字符串,带有转换方法:

const c = red(3, 5);
`${c}`             // → '#ab34cd' (string coercion)
'bg: ' + c         // → 'bg: #ab34cd' (concatenation)
c.hex()            // → '#ab34cd'
c.hsl()            // → 'hsl(280, 60%, 50%)'
c.rgb()            // → 'rgb(171, 52, 205)'
c.oklch()          // → 'oklch(52.3% 0.198 310)'
c.luminance        // → 0.52 (perceptual, 0–1)

使用 .format() 用于修改默认输出格式的颜色空间 :

const rgbSpace = new PlaneColorSpace('#000', '#fff', '#f00').format('rgb').size(6);
`${rgbSpace(3, 5)}`  // → 'rgb(255, 128, 128)'
rgbSpace(3, 5).hex() // → '#ff8080' (still available)

图像调色板提取

从图像中提取出有三级分析的色调色板:生来独特的色调,主色调色团,和ANSI分类调色板.

要求数 fast-png 财务报告和审定财务报表 jpeg-js (编为附属单位). 支持PNG和JPEG文件.

palette(filePath)

import { palette } from '@basiclines/rampa-sdk';

const p = await palette('photo.jpg');

主要颜色

通过 OKLCH 空间中的 k- means 集群, 顶部 N 颜色组 :

p.dominant()                     // → PaletteEntry[] (top 10)
p.dominant({ count: 5 })        // top 5
p.dominant({ tolerance: 10 })   // wider clustering (default: 4)

// Shortcut with .at() (0-based, like ramp.at())
p.at(0)                          // most dominant color
p.at(0).color.hex               // → '#2d2a18'
p.at(0).frequency               // → 0.278 (27.8% of pixels)
p.at(0).color.lighten(0.1).hex  // chain transforms

原始调色板

所有有近重复的独特的颜色合并:

p.raw()                          // → PaletteEntry[]
p.raw({ tolerance: 3 })         // deltaE merge threshold (default: 2)
p.raw({ maxColors: 500 })       // cap output (default: 1000)

ANSI 调色板

归入终端颜色类别的颜色 :

p.ansi()
// → { red: PaletteEntry[], green: [...], blue: [...], ... }

p.ansi({ count: 3 })            // max 3 per category (default: 5)

类别 : black, (中文(简体) ), red, (中文(简体) ), green, (中文(简体) ), yellow, (中文(简体) ), blue, (中文(简体) ), magenta, (中文(简体) ), cyan, (中文(简体) ), white

由 OKLCH 属性分组

通过光度、染色体或色调将颜色组合成桶:

p.group({ by: 'L' })            // → { darkest, dark, mid, light, lightest }
p.group({ by: 'C' })            // → { gray, muted, saturated, vivid }
p.group({ by: 'H' })            // → { red, orange, yellow, green, cyan, blue, purple, pink }

p.group({ by: 'L', count: 3 })  // max 3 colors per bucket
p.group({ by: 'L', tolerance: 10 })  // wider dedup within buckets

自定义桶边框 :

p.group({
  by: 'L',
  buckets: [
    { name: 'dark', min: 0, max: 0.3 },
    { name: 'mid',  min: 0.3, max: 0.7 },
    { name: 'light', min: 0.7, max: 1.0 },
  ],
})

排序与 .sortBy()

所有阵列和分组成果支助 .sortBy() 用于重排:

// Sort dominant colors by lightness (dark → light)
p.dominant({ count: 5 }).sortBy('L')

// Sort within each group bucket
p.group({ by: 'C' }).sortBy('L')    // chroma groups, each sorted dark→light
p.ansi().sortBy('L')                 // ANSI categories, each sorted dark→light

// Sort fields: 'L' (lightness), 'C' (chroma), 'H' (hue), 'frequency'
p.raw().sortBy('H')                  // all colors sorted by hue angle

// Chainable — returns a new sorted result
p.dominant().sortBy('L').sortBy('C')

额外

p.average()                      // → Color (weighted OKLCH average)
p.temperature()                  // → 'warm' | 'cool' | 'neutral'

产出

p.output('json')                 // full analysis as JSON
p.output('css', 'photo')        // CSS custom properties
p.output('text')                 // readable text

调色板 Entry 形状

interface PaletteEntry {
  color: Color;       // full Color with transforms
  frequency: number;  // 0-1, percentage of sampled pixels
}

发展

cd sdk
bun install

# Run tests
bun test

# Build
bun run build

版本与发布记录

@basiclines/rampa-sdk 共发布 15 个版本,首次发布于 2026/02/20;过去 12 个月发布了 15 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
6.0.0latest2026/03/217 个月前
5.0.02026/03/137 个月前
4.0.02026/03/097 个月前
3.1.02026/03/058 个月前
3.0.02026/03/048 个月前
2.1.02026/02/288 个月前

关于 @basiclines/rampa-sdk 的常见问题

@basiclines/rampa-sdk 是什么?

程序化 JavaScript SDK 用于生成带有斜坡的调色板

如何安装 @basiclines/rampa-sdk?

在项目目录运行 npm install @basiclines/rampa-sdk,或使用 pnpm add / yarn add / bun add。

@basiclines/rampa-sdk 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@basiclines/rampa-sdk 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@basiclines/rampa-sdk 可以商用吗?

@basiclines/rampa-sdk 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@basiclines/rampa-sdk 的下载量有多少?

根据 npm 官方下载统计,@basiclines/rampa-sdk 在 2026/10/08 – 2026/11/06 这 30 天内被下载 25,088 次,日均约 836 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@basiclines/rampa-sdk 还在维护吗?

最新版本 6.0.0 发布于 2026/03/21(7 个月前);至今共发布 15 个版本,其中过去 12 个月发布了 15 个;首次发布于 2026/02/20。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。