Color Conversion

2 min read

Color Conversion

Convert color into different formats.

Usage

# colorToArray(color: Color, colorModel?: ColorModel) => number[]

Convert Color into array. The default value of colorModel is the color model used in color.

import { colorToArray } from '@antv/smart-color';

const color = {
  model: 'rgb',
  value: { r: 91, g: 143, b: 249 },
};

colorToArray(color); // [91, 143, 249]
colorToArray(color, 'hsv'); //[ 220.25316455696202, 0.6345381526104418, 0.9764705882352941 ]
# arrayToColor(array: number[], colorModel?: ColorModel) => Color

Convert array into Color. The default value of colorModel is "rgba" if the length of the array is 4, otherwise the default value of colorModel is "rgb".

import { arrayToColor } from '@antv/smart-color';

arrayToColor([91, 143, 249]);
// {
//   model: "rgb",
//   value: { r: 91, g: 143, b: 249 },
// }

arrayToColor([220.25, 0.63, 0.98], 'hsv');
// {
//   model: "hsv",
//   value: { h: 220.25, s: 0.63, v: 0.98 },
// }
# colorToHex(color: Color) => string

Convert Color into hexadecimal string.

import { colorToHex } from '@antv/smart-color';

const color = {
  model: 'rgb',
  value: { r: 91, g: 143, b: 249 },
};

colorToHex(color); // #5b8ff9
# hexToColor(hex: string) => Color

Convert hexadecimal string into Color.

import { hexToColor } from '@antv/smart-color';

hexToColor('#5b8ff9');
// {
//   model: "rgb",
//   value: { r: 91, g: 143, b: 249 },
// };
# colorToGray(color: Color) => number

Convert Color into gray number.

import { colorToGray } from '@antv/smart-color';

const color = {
  model: 'rgb',
  value: { r: 91, g: 143, b: 249 },
};

colorToGray(color); // 140
# nameToColor(name: string) => Color

Convert valid css color name into Color.

import { nameToColor } from '@antv/smart-color';

nameToColor('moccasin');
// {
//   model: 'rgb',
//   value: { r: 255, g: 228, b: 181 },
// });

nameToColor('aliceblue');
// {
//   model: 'rgb',
//   value: { r: 240, g: 248, b: 255 },
// });