stringToColor()
此函数属于 Iconify Utils 包。
函数 stringToColor() 将字符串转换为 Color 对象,出错时返回 null。
此函数可用于验证用户输入。它支持颜色关键字、十六进制颜色、RGB、HSL、LAB 和 LCH 颜色。不支持变量,因为该函数旨在解析 SVG,而 SVG 不应引用任何外部变量。
用法
函数包含一个参数:
- value,string 类型。颜色字符串。
函数成功时返回 Color 对象,出错时返回 null。
可能的值
函数可转换的颜色:
- 关键字,例如 "red"。
- 十六进制颜色,例如 "#ff0000",也支持简写形式和带 Alpha 通道的格式。
- 几种函数表示法:
- RGB:"rgba(255, 0, 0, 1)"。
- HSL:"hsla(0, 50%, 50%, 1)"。
- LAB:"lab(50% 86 40 / 1)"。
- LCH:"lch(50% 86 40 / 1)"。
- 几个特殊关键字:
- "transparent"
- "none"
- "currentColor"
详情请参阅 Color 类型说明。
示例
demo.ts
ts
import { stringToColor } from '@iconify/utils';
// { type: 'rgb', r: 128, g: 0, b: 128, alpha: 1 }
console.log(stringToColor('purple'));
// { type: 'rgb', r: 255, g: 0, b: 0, alpha: 1 }
console.log(stringToColor('#f00'));
// { type: 'rgb', r: 136, g: 32, b: 50, alpha: 0.8784313725490196 }
console.log(stringToColor('#882032E0'));
// { type: 'rgb', r: 255, g: 48, b: 0, alpha: 0.5 }
console.log(stringToColor('rgba(255, 48, 0, 0.5)'));
// { type: 'rgb', r: 255, g: 127.5, b: 63.75, alpha: 0.25 }
console.log(stringToColor('rgba(100% 50% 25% 25%)'));
// { type: 'transparent' }
console.log(stringToColor('rgba(255, 0, 0, 0)'));
// { type: 'hsl', h: 0, s: 50, l: 50, alpha: 1 }
console.log(stringToColor('hsl(0, 50%, 50%)'));
// { type: 'hsl', h: 200, s: 20, l: 70, alpha: 0.5 }
console.log(stringToColor('hsla(200, 20%, 70%, .5)'));
// { type: 'lch', l: 54.292, c: 106.839, h: 40.853, alpha: 1 }
console.log(stringToColor('lch(54.292% 106.839 40.853)'));
// { type: 'lab', l: 52.2345, a: 40.1645, b: 59.9971, alpha: 0.5 }
console.log(stringToColor('lab(52.2345% 40.1645 59.9971 / .5)'));
// { type: 'transparent' }
console.log(stringToColor('transparent'));
// { type: 'none' }
console.log(stringToColor('none'));
// { type: 'current' }
console.log(stringToColor('currentColor'));
// null
console.log(stringToColor('whatever'));
console.log(stringToColor('inherit'));
console.log(stringToColor('color(display-p3 0 1 0)'));